laravel - 如何在同一台服务器上部署分离的后端和前端
问题描述
我开发了一个以 Vuejs 作为前端,Laravel 作为后端 api 的项目。在 localhost 中它们运行在不同的端口。我应该如何将它们部署到生产中?
解决方案
当您为生产构建 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
包含的所有内容。dist
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
,我们现在应该看到我们可以使用 向 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]
推荐阅读
- fortran - 字符声明表
- c# - 在 Azure 认知搜索中处理单复数搜索词
- junit - 使用条件制作自定义类范围的 JUnit 注释
- directx - DirectX11可以将负值写入纹理格式化的浮点数吗?
- azure-devops - 链接到 KeyVault 的 Azure DevOps 变量组的“全选”选项
- excel - 遍历列,如果值为 1,则从上面复制并粘贴
- ios - apns-collapse-id (iOS) 如何与 Firebase 一起使用?
- jquery - jquery 遍历 div 的正确顺序不起作用?
- wordpress - 将 Docker 容器连接到 GitHub - 当使用 docker-compose.yml 创建 docker 映像时
- c++ - 直接在函数调用时将向量(从函数返回)复制到另一个向量的特定点,而不需要额外的临时变量 [c++]