Nginx路径重写


问题

  • 经常遇到前后端分离项目部署时候,前端请求的路径会多加一层路径

比如我的

​ 前端地址是:http://baidu.com,后端地址是:http://taobao.com

那么前端如果直接写死后端地址的话,一是要处理跨域问题,二是如果后端换地址需要改前端代码

最好的办法就是通过反向代理,比如http://baidu.com/api然他指向http://taobao.com,把**/api**替换掉就好了

像vue有vue.config.js中配置反向代理来重写路径,但实际环境大多数是用专门的反向代理

  • 直接设置为后端的真实地址

需要改前端代码,如果部署多个服务器就要改n次,很不灵活,而且存在跨域问题也要解决

  • 利用宝塔的nginx配置反向代理

虽然可以配置,但是存在奇怪的bug,设置了内容替换,在的服务器可以生效,有的不能生效

image-20220712111445793


解决

  • 宝塔直接设置反向代理 *==FAIL==

配置文件:

location /stage-api
{
    proxy_pass http://127.0.0.1:6501;
    proxy_set_header Accept-Encoding "";
    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 REMOTE-HOST $remote_addr;

    #add_header X-Cache $upstream_cache_status;

    #Set Nginx Cache

    proxy_set_header Accept-Encoding "";
    sub_filter "/stage-api" "/";
    sub_filter_once on;
        add_header Cache-Control no-cache;
}

主要就是用到sub_filter

通过一番检索说sub_filter需要把gzip关闭才可以用,否则不生效,但我关了还是不生效

  • 修改配置文件 *==PASS==

修改后的配置文件如下:

location /stage-api
{
    proxy_pass http://127.0.0.1:6501;
    proxy_set_header Accept-Encoding "";
    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 REMOTE-HOST $remote_addr;

    #add_header X-Cache $upstream_cache_status;

    #Set Nginx Cache

    proxy_set_header Accept-Encoding "";
    #sub_filter /stage-api /;
    #sub_filter_once on;
    rewrite  ^/stage-api/(.*)  /$1 break;
        add_header Cache-Control no-cache;
}

注释掉sub_filter

用 rewrite完美解决!

image-20220712112956120

本文由博客一文多发平台 OpenWrite 发布!

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐