转自:前后端分离Nginx部署解决方案 · 语雀
一、获取前端代码编译发布步骤
- 执行cnpm install/npm install安装项目依赖
- 执行npm run build构建编译生成dist文件该文件即为【项目发版代码】
二、服务器安装部署
- 将代码放置在你认为合适的目录该目录为Nginx server 中需要执行项目的路径【参考下面配置示例】
三、解决vue使用的是vue-router的history模式时需要此配置
location / {
try_files $uri $uri/ /index.html;
}
// 5.由于项目为前后分离部署需要为前端提供接口调用使用
// Nginx server需要proxy如下配置 ,proxy 指向地址为后端服务地址
// 配置proxy代理路径 可以配置多个proxy
location ~ /api/ {
proxy_pass http://api.xxxxx.com;//此地址为后端API服务器地址
}
或
location ~ /api/ {
proxy_pass http://api.xxxxx.com:8081;//此地址为后端API服务器地址
}
// Nginx server 配置示例如下:
server {
listen 80;//此为端口配置
server_name localhost;//此为网站域名配置
set $root_path '/opt/fe-code/dist';//此为项目代码路径配置
root $root_path;
index index.html index.htm index.php;
try_files $uri $uri/ @rewrite;
if ( $host ~* (.*)\.(.*)\.(.*) ) {
set $domain $1;
}
location @rewrite {
rewrite ^/(.*)$ /index.php?_url=/$1&_ename=$domain;
}
location ~* ^/(css|img|js|flv|swf|download)/(.+)$ {
root $root_path;
}
#解决vue使用的是vue-router的history模式时刷新页面出现404的问题
location / {
try_files $uri $uri/ /index.html;
}
//此为proxy 配置地址为API请求地址 proxy /api/ 为正则匹配路由如果匹配到则跳转到后端服务,否则走前段路由
location ~ /api/ {
proxy_pass http://api.xxxxx.com;//此地址为API请求地址
}
//此为proxy 配置地址为API请求地址 proxy /upload/ 为正则匹配路由如果匹配到则跳转到后端服务,否则走前段路由
location ~ /upload/ {
proxy_pass http://127.0.0.1:8080;//此地址为API请求地址
}
location ~ /\.ht {
deny all;
}
}