Nginx 部署 Vue 前后端分离应用到子路径
Vue 前端带子路径打包
可参考章节:vue-cli 分环境打包,原理差不多,改 context path,比较简单,此处不再赘述。
假如前端设置的子路径 context path=/dev/,后端 api 接口根路径为:/dev-api/
浏览器想从 http://localhost:80/dev/index(或 http://localhost:80/dev/index.html)访问应用
nginx.conf 配置
shell
#user nobody;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
client_max_body_size 1024m;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
server {
listen 80;
server_name www.aday.fun;
# 访问 http://localhost:80/dev/index 或 http://localhost:80/dev/index.html
# 注:访问时,不能省略 /index 或 /index.html
location /dev/ {
alias /usr/share/nginx/dev/;
try_files $uri $uri/ /dev/index.html;
index index.html index.htm;
}
# 访问 http://localhost:80/
location / {
root html;
try_files $uri $uri/ /index.html;
index index.html index.htm;
}
# 访问 http://localhost:80/ 对应的后端服务
location /prod-api/ {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://localhost:8080/;
}
# 访问 http://localhost:80/dev/index 对应的后端服务
location /dev-api/ {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://localhost:8081/;
}
}
}
重启 nginx
shell
# 执行reload命令,使配置生效
systemctl daemon-reload
# 重新加载
systemctl reload nginx.service
浏览器访问
- 访问 http://localhost:80/ 则转发至 /usr/share/nginx/html 前端工程,使用后端 /prod-api/ 前缀的接口服务。
- 访问 http://localhost:80/dev/index 则转发至 /usr/share/nginx/dev 前端工程,使用后端 /dev-api/ 前缀的接口服务。