szmdx.cn szmdx.cn

欢迎光临
我们一直在努力
顶部
域名

nginx配置请求转发不生效的实现_nginx_

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 请求转发不生效内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。
发布内容
-六神源码网 -六神源码网