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。
到此这篇关于nginx配置请求转发不生效的实现的文章就介绍到这了,更多相关nginx 请求转发不生效内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!