公告

特别推出京东优惠挖掘小程序 [点击这里,扫码收藏] 专门收集京东今日特价爆品,商家漏洞等,拼手速,手慢无! 新增优惠: 1,美团外卖红包:扫码至少节省3元[点击收藏],全国可用,用完还能领。 2,车主加油打折服务:一键导航到加油站,选择油枪,支付时直减。 [点击查看] 3,电影票购买返利,覆盖所有主流院线。 [点击查看]

#1 2023-06-04 09:52:05

小天天
Moderator
注册时间: 2019-09-29
帖子: 886

nginx location proxy

1、proxy_pass ip+port后面有斜杠/或者path/xxx,新的ip路径是:

proxy_pass + 访问路径除去location相同部分路径。

2、proxy_pass 只有ip+port,新的路径:

proxy_pass + location + 访问路径除去location相同路径。

离线

#2 2023-09-07 17:59:46

小天天
Moderator
注册时间: 2019-09-29
帖子: 886

Re: nginx location proxy

If a location is defined by a prefix string that ends with the slash character, and requests are processed by one of proxy_pass, fastcgi_pass, uwsgi_pass, scgi_pass, memcached_pass, or grpc_pass, then the special processing is performed. In response to a request with URI equal to this string, but without the trailing slash, a permanent redirect with the code 301 will be returned to the requested URI with the slash appended. If this is not desired, an exact match of the URI and location could be defined like this:

location /user/ {
    proxy_pass http://user.example.com;
}

location = /user {
    proxy_pass http://login.example.com;
}

离线

#3 2023-10-26 11:36:15

小天天
Moderator
注册时间: 2019-09-29
帖子: 886

Re: nginx location proxy

由于web页面或静态资源内写死了类似的绝对路径,比如src=/...;  href=/...,那么对于用户来说,通过页面内的链接进行跳转时,都会请求到nginx服务对应的路径上。一旦存在另一个服务也包含类似的路径,也需要nginx进行代理,那么矛盾就出现了:访问nginx的同一个路径下的请求究竟转发给哪一个服务?

要解决这个问题,必须在用户收到报文前,将报文的数据中包含的绝对路径都添加统一的前缀,如/my/public,/my/api,/my/login,这样nginx代理配置则可以简化为:

location /my/ {
    proxy_pass http://my_server/;
    proxy_set_header Host $host:$server_port;

    proxy_redirect / /my/;
}
location /other/ {
    proxy_pass http://other_server/;
    proxy_set_header Host $host:$server_port;

    proxy_redirect / /other/;
}
nginx的ngx_http_sub_module模块提供了类似的报文数据替换功能,该模块默认不会安装,需要在编译nginx时添加--with-http_sub_module参数,或者直接下载nginx的rpm包。

使用sub_filter对数据包进行替换的语法如下:

location /my/ {
    proxy_pass http://my_server/;
    proxy_set_header Host $host:$server_port;
   
    sub_filter 'href="/' 'href="/my/';
    sub_filter 'src="/' 'src="/my/';
    sub_filter_types text/html;
    sub_filter_once  off;
}
上述配置会将/my/下的所有响应报文内容的href="/替换为href="/my,以及src="/替换为src="/my,即为所有的绝对路径添加公共前缀。

注意,如果需要配置多个sub_filter,必须保证nginx是1.9.4版本之上的。

总结
即便如此,sub_filter也不能解决所有问题。目前流行的js框架都会有自动渲染url的功能,也就是说,很多绝对路径并非写死在静态页面内,也是由js代码框架动态生成的,面对这样的情况,sub_filter也是无能为力了。对于这样的情况,笔者只能由衷地奉劝,还是安静的改代码吧!

最近编辑记录 小天天 (2023-10-26 11:36:44)

离线

页脚

Powered by 华新企财帮

京ICP备19031397号-1