首页 > 网站 > Nginx > 正文

详解proxy_pass根据path路径转发时的"/"问题记录

2024-08-30 12:24:49
字体:
来源:转载
供稿:网友

在nginx中配置proxy_pass时,如果是按照^~匹配路径时,要注意proxy_pass后的url最后的/。当加上了/,相当于是绝对根路径,则nginx不会把location中匹配的路径部分代理走;如果没有/,则会把匹配的路径部分也给代理走。

比如下面设置:

location ^~ /wangshibo/{proxy_cache js_cache;proxy_set_header Host js.test.com;proxy_pass http://js.test.com/;}

如上面的配置,如果请求的url是http://servername/wangshibo/test.html会被代理成http://js.test.com/test.html

而如果这么配置

location ^~ /wangshibo/{proxy_cache js_cache;proxy_set_header Host js.test.com;proxy_pass http://js.test.com;}

则请求的url是http://servername/wangshibo/test.html会被代理到http://js.test.com/wangshibo/test.html

当然,可以用如下的rewrite来实现/的功能

location ^~ /wangshibo/{proxy_cache js_cache;proxy_set_header Host js.test.com;rewrite /wangshibo/(.+)$ /$1 break;proxy_pass http://js.test.com;}

列举下面一例

1)第一种配置

[root@BJLX_16_202_V vhosts]# cat ssl-wangshibo.confupstream at {  server 192.168.1.202:8080 max_fails=3 fail_timeout=30s;}  server {  listen 443;  server_name www.wangshibo.com;  ssl on;    ### SSL log files ###  access_log logs/wangshibo_access.log;  error_log logs/wangshibo_error.log;  ### SSL cert files ###  ssl_certificate ssl/wang.cer;    ssl_certificate_key ssl/wang.key;    location /attendance/ {  proxy_pass http://at;                             //不需要加上"/"            proxy_next_upstream error timeout invalid_header http_500 http_502 http_503;  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 X-Forwarded-Proto https;  proxy_redirect off;    }  }

访问https://www.wangshibo.com/attendance/和http://192.168.1.202:8080/attendance结果是一致的。

2)第二种配置

[root@BJLX_16_202_V vhosts]# cat ssl-wangshibo.confupstream at {  server 192.168.1.202:8080 max_fails=3 fail_timeout=30s;}  server {  listen 443;  server_name www.wangshibo.com;  ssl on;    ### SSL log files ###  access_log logs/wangshibo_access.log;  error_log logs/wangshibo_error.log;  ### SSL cert files ###  ssl_certificate ssl/wang.cer;    ssl_certificate_key ssl/wang.key;    location / {  proxy_pass http://at/attendance/;                         //一定要加上"/"              proxy_next_upstream error timeout invalid_header http_500 http_502 http_503;  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 X-Forwarded-Proto https;  proxy_redirect off;    }  }

访问https://www.wangshibo.com和http://192.168.1.202:8080/attendance结果是一致的。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表