当前位置: 代码网 > it编程>数据库>MsSqlserver > nginx配置请求转发不生效的实现

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

2025年02月12日 MsSqlserver 我要评论
bug description将vue打包部署时,修改了nginx.conf,在nginx.conf中配置了请求转发,但是请求转发不生效,请求返回状态码404。nginx配置如下:location ~

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

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com