如何在同一台服务器上部署分离的后端和前端

How to deploy separated backend and frontend on same server

我开发了一个项目,以 Vuejs 作为前端,Laravel 作为后端 api.In localhost 他们 运行 在不同的 ports.How 我应该部署他们在生产中?

当您构建用于生产的 Vue 应用程序时,所有相关文件都在 dist 文件夹中。它不会 运行 在任何端口上,而是文件由网络服务器(例如 Apache 或 Nginx)提供服务。对于 laravel api,您通常可以看到 laravel 安装中的 public 文件夹,同时无法直接从 Web 访问其余文件。

我假设您想将 api 和前端部署在同一个域中。让它工作的最简单方法是为您的 api 设置一个特定的前缀。在下面的例子中,我对所有 api 请求使用前缀 /api,因为这是 api 路由的默认值。任何其他的都被认为是对前端的请求。

您设置文件夹结构如下。 public_html 文件夹是转到 example.com 时通常加载的文件夹,您可以通过添加包含一些内容的 test.txt 文件并转到 example.com/test.txt 来测试它。 backend 文件夹包含您的 laravel 安装。 frontend 文件夹包含 dist 文件夹在 运行ning npm run build.

之后包含的所有内容
/var
+-- /www
    +-- /vhosts
        +-- /example.com
            +-- public_html
        +-- /backend
        +-- /frontend

为了让一切正常工作,我们将删除 public_html 文件夹并将其替换为指向 backend/public 的符号链接。

cd /var/www/vhosts/example.com
rm -r public_html
ln -s ../backend/public public_html

当我们检查 example.com 时,我们现在应该看到我们可以使用 example.com/api/someroute 向 api 发出请求。我们可以通过多种方式让前端使用它,但为了便于部署,让我们创建一个指向 dist 文件夹的符号链接。

cd /var/www/vhosts/example.com/public_html
ln -s ../../frontend/dist app

如果您正在为您的 Vue 应用程序使用哈希模式并且不介意通过 example.com/app 访问该应用程序,我相信这就是您需要做的全部。否则,如果您使用的是 Apache,则需要修改 .htaccess 文件,或者更改您正在使用的任何其他网络服务器的重写配置。我想象 .htaccess 文件看起来像这样:

# We assume that the FollowSymLinks option is enabled in the main Apache configuration.
RewriteEngine On

# Rewrite anything that starts with `api` to the laravel index file
RewriteCond %{REQUEST_URI} ^/api
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

# Rewrite anything else to the frontend app
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /app/index.html [L]