Nginx配置proxy_pass转发的/路径问题

本文详细解析了在Nginx中使用proxy_pass时的路径匹配规则,特别是^~匹配方式下,结尾斜杠对代理行为的影响,并提供了一种通过rewrite指令实现特定代理功能的方法。

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

location ^~ /static_js/ 

proxy_cache js_cache; 
proxy_set_header Host js.test.com; 
proxy_pass http://js.test.com/
}

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

而如果这么配置

location ^~ /static_js/ 

proxy_cache js_cache; 
proxy_set_header Host js.test.com; 
proxy_pass http://js.test.com
}

则会被代理到http://js.test.com/static_js/test.htm

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

location ^~ /static_js/ 

proxy_cache js_cache; 
proxy_set_header Host js.test.com; 
rewrite /static_js/(.+)$ /$1 break; 
proxy_pass http://js.test.com

 


本文转自 lover00751CTO博客,原文链接:http://blog.51cto.com/wangwei007/1103734,如需转载请自行联系原作者


使用Java和Nginx的`proxy_pass`指令进行页面路径转发可通过如下方式操作: ### 域名转发到本地Java应用端口 若要将域名转发到本地运行的Java应用端口(如Tomcat默认的8080端口),可在Nginx配置文件里添加如下配置: ```nginx server{ listen 80; server_name tomcat.shaochenfeng.com; index index.php index.html index.htm; location / { proxy_pass http://127.0.0.1:8080; proxy_set_header Host $proxy_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } ``` 此配置把访问`tomcat.shaochenfeng.com`的请求转发到本地的8080端口,并且设置了请求头,让Java应用能收到真实的请求信息[^1]。 ### 区分前端和后端路径转发 当存在H5前端和Java后端时,可在Nginx配置文件里分别对前端静态资源和后端Java接口进行配置: ```nginx server { listen 82; server_name localhosts; location / { root /usr/soft/nginx/html/threephone; index index.html index.htm; } location /prod-api/ { proxy_pass http://ip:8080/; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } ``` 在这个配置中,访问根路径`/`时,Nginx会返回指定目录下的前端静态页面;访问`/prod-api/`开头的路径时,请求会被转发到`http://ip:8080/`的Java后端服务[^2]。 ### location与proxy_pass配置规则 在配置`location`和`proxy_pass`时,需要留意相关规则。`location`进行的是模糊匹配,没有“/”结尾时,`location /abc/def`能匹配`/abc/defghi`请求,也能匹配`/abc/def/ghi`等;有“/”结尾时,`location /abc/def/`不能匹配`/abc/defghi`请求,仅能匹配`/abc/def/anything`这样的请求。`proxy_pass`用于配置转发规则,可根据实际需求设置转发的目标地址[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值