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

时间:2019-02-16 13:48:16

标签: laravel vue.js deployment frontend backend

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

1 个答案:

答案 0 :(得分:2)

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

我将假设您要在同一域上部署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时,现在应该看到我们可以使用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文件,或者更改正在使用的任何其他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]
相关问题