首先,我们先上两个例子
location ^~ /test/
{
proxy_pass http://www.test.com;
}
location ^~ /test/
{
proxy_pass http://www.test.com/;
}
区别只在于proxy_pass转发的路径后是否带 “/“,
针对不带/, 假如我们访问的url=http://www.test.com/test/test.php,
则通过nginx代理后,请求的路径访问地址为http://www.test.com/test/test.php
针对带/, 假如我们访问的url=http://www.test.com/test/test.php,
则通过nginx代理后,请求的路径访问地址为http://www.test.com/test.php
实现上述效果也可以通过rewrite来实现,代码如下
location ^~ /test/
{
proxy_set_header Host www.test.com;
rewrite /test/(.+)$ /$1 break;
proxy_pass http://www.test.com;
}
proxy_set_header 解析
proxy_set_header
Syntax: proxy_set_header field value
Default: Host $proxy_host / Connection close
Context: http / server / location
Reference: proxy_set_header
当nginx作为反向代理使用,而如果后端服务器有防盗链或根据http请求头中的host字段来进行路由或判断功能的话,如nginx不重写请求头中的host字段,将会导致请求失败【默认反向代理服务器会向后端服务器发送请求,并且请求头中的host字段应为proxy_pass指令设置的服务器】
同理,X_Forward_For字段表示该条http请求是有谁发出的,如果反向代理服务器不重写该请求头的话,那么后端服务器在处理时会认为所有的请求都来在反向代理服务器,如果后端有防攻击策略的话,那么机器就无法访问了。
因此,一般我们用以下nginx中增加以下配置:
proxy_set_header Host $http_host;
proxy_set_header X-Forward-For $remote_addr;
需要注意的是:如果Host请求头部没有出现在请求头中,则$http_host值为空,但是$host值为主域名。因此,一般而言,会用$host代替$http_host变量,从而避免http请求中丢失Host头部的情况下Host不被重写的失误。
proxy_pass 与 tomcat session丢失
闲言少叙,直接看nginx修改前后的配置文件:
location / {
proxy_pass http://10.44.15.43:8080/MP/;
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;
}
修改后的配置文件:
location / {
proxy_pass http://10.44.15.43:8080/MP/;
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_set_header Cookie $http_cookie;
add_header From admin.weiwei.com.cn;
proxy_cookie_path /MP/ /;
chunked_transfer_encoding off;
}
问题分析:原来配置会导致cookie存储的位置不是基于“/”那么在第二次访问的时候会从新创建session,因此session中的信息丢失,因此修改cookeie的存储路径解决问题。