发布vue项目、nginx配置及问题场景(history)
场景
- 我想使用一个nginx配置多个程序页面
- 使用alias时刷新和退出时会404,或者退出路由不对
实现
在env环境变量中配置 前置路径
VUE_APP_PATH = '/'
VUE_APP_PATH = '/middle-platform-manager/'
router /index.js(路由配置文件)
export default new Router({mode: 'history', // 去掉url中的#scrollBehavior: () => ({ y: 0 }),routes: constantRoutes,base: process.env.VUE_APP_PATH # 加入环境信息
})
修系统中的location.href 连接
location.href = process.env.VUE_APP_PATH + 'index'
vue.config.js
publicPath: process.env.VUE_APP_PATH,
nginx配置
server {listen 80;listen [::]:80;server_name localhost;#access_log /var/log/nginx/host.access.log main;location /prod-api/ {proxy_pass http://middle-platform-server:8080/;charset utf-8;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-Forwarded-Proto $scheme;#add_header Content-Type 'text/html; charset=utf-8';}# location / {# alias /usr/share/nginx/html/;# index index.html index.htm;# }location / {set $flag 0;#获取url完整请求set $URL $host$request_uri;if ($URL ~ "/middle-platform-manager/"){set $flag 1;root /usr/share/nginx/html/middle-platform-manager/;}if ($flag = 0){root /usr/share/nginx/html/;}index index.html index.htm;autoindex on;}location /middle-platform-manager {alias /usr/share/nginx/html/middle-platform-manager/;try_files $uri $uri/ /index.html;autoindex on;}#error_page 404 /404.html;# redirect server error pages to the static page /50x.html## error_page 500 502 503 504 /50x.html;# location = /50x.html {# root /usr/share/nginx/html;# }# proxy the PHP scripts to Apache listening on 127.0.0.1:80##location ~ \.php$ {# proxy_pass http://127.0.0.1;#}# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000##location ~ \.php$ {# root html;# fastcgi_pass 127.0.0.1:9000;# fastcgi_index index.php;# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;# include fastcgi_params;#}# deny access to .htaccess files, if Apache's document root# concurs with nginx's one##location ~ /\.ht {# deny all;#}
}
之后遇到的其他的问题
因为用的是ruoyi的框架,改完后,点击登录,发现还是匹配不上,后面排查发现是因为login.vue登录成功跳转的时候路径变成了 ‘/middle-platform-manager//home/index’, 中间多了个 ‘/‘导致nginx匹配不上,需要再push路径的时候,处理router路由开头的’/’,部署后就完美解决了,退出、刷新、等了都没问题了