nginx 反向代理替换URL

问题探究

今天在运营在推进业务时不小心将用户访问地址给错了,原本是https://test.com/web/store/webh5,推送给用户的地址变为了:https://test.com/web/store/webh6,导致用户访问页面404。

解决办法:

用NGINX将错误地址重定向到正确地址中去

解决实例

nginx 提供反向代理服务,日常开发过程中有时候我们需要使用nginx 作为代理服务根据url的不同去访问不同的服务器或者不同端口,提供如下方案。、

直接替换location  匹配部分

1.proxy_pass的目标地址,默认不带/,表示只代理域名,url和参数部分不会变(把请求的path拼接到proxy_pass目标域名之后作为代理的URL)

2.如果在目标地址后增加/,则表示把path中location匹配成功的部分剪切掉之后再拼接到proxy_pass目标地址
 

server {
        listen       80;
        server_name  localhost;
location /webh5 {           
        proxy_pass        http://127.0.0.1:8080;
        proxy_redirect    off;
        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_pass  以/结尾
location /webh6 {           
        proxy_pass        http://127.0.0.1:8080/;
        proxy_redirect    off;
        proxy_set_header  Host  $host;
        proxy_set_header  X-Real-IP  $remote_addr;
        proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;			
		}
        }

例如:https://test.com/web/store/webh5

如上两个匹配成功后,实际代理的目标url分别是

http://127.0.0.1:8080/web/store/webh5 (将 /webh5 拼接到  proxy_pass      的  http://127.0.0.1:8080 之后)

http://127.0.0.1:8080/web/store/webh5 (匹配访问路径中带有 webh6 将地址重定向为 http://127.0.0.1:8080/web/store/webh5)

注:由于页面是由nginx代理接收请求 所以重定向地址为 127.0.0.1:8080 (8080为nginx端口)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值