Bug Description
将vue打包部署时,修改了nginx.conf,在nginx.conf中配置了请求转发,但是请求转发不生效,请求返回状态码404。
nginx配置如下:
location ~ ^/api(/|$) {
proxy_next_upstream http_500 http_502 http_503 http_504 error timeout invalid_header;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://localhost:8081; #代理的ip
expires 24;
}
Reproduction Steps
1.编写vue项目,使用npm run build打包,将打包后的文件夹dist放到nginx的html目录下。
2.修改nginx.conf,配置请求转发。
3.启动nginx服务。
Reason
在本地开发环境,为了解决跨域问题,修改了vue.config.js:
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8081',
changeOrigin: true,
pathRewrite: { '^/api': '' },
ws: true,
secure: false
}
}
}
此处做了路由改写,实际后端访问地址为http://localhost:8081/
,而nginx配置的代理地址为http://localhost:8081/api
,导致请求定向错误。
Solution
将nginx.conf进行路由改写:
location ~ ^/api(/|$) {
proxy_next_upstream http_500 http_502 http_503 http_504 error timeout invalid_header;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://localhost:8081; #代理的ip
# 将 /api 替换为 /
rewrite ^/api(.*)$ $1 break;
expires 24;
}
正常转发,请求返回状态码200。