首页 > 解决方案 > 如何在同一台服务器上部署分离的后端和前端

问题描述

我开发了一个以 Vuejs 作为前端,Laravel 作为后端 api 的项目。在 localhost 中它们运行在不同的端口。我应该如何将它们部署到生产中?

标签: laravelvue.jsdeploymentfrontendbackend

解决方案


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

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

您设置文件夹结构,如下所示。该public_html文件夹是通常在转到时加载的内容example.com,您可以通过添加test.txt包含一些内容的文件并转到example.com/test.txt. 该backend文件夹包含您的 laravel 安装。该文件夹包含该文件夹在运行后frontend包含的所有内容。distnpm 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,我们现在应该看到我们可以使用 向 api 发出请求example.com/api/someroute。有几种方法可以让前端使用它,但为了便于部署,让我们创建一个指向 dist 文件夹的符号链接。

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

如果您正在为您的 Vue 应用程序使用哈希模式并且不介意通过 访问该应用程序example.com/app,我相信这就是您需要做的所有事情。否则,如果您使用的是 Apache,则需要修改该.htaccess文件,或者更改您正在使用的任何其他 Web 服务器的重写配置。我想.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]

推荐阅读