nginx 处理header 全攻略
时间:2010-11-12 来源:Enoch
公司的网站要加入动态加速 一个直接的问题是经过转发 客户端请求的头被改了一部分 remote_addr这个被改成了自定义的True-Client-IP 为了不改动已有的程序 需要在nginx那转发的时候把这个头重新打到Remote_Addr 上
要实现这个 有两个关键点 现记录如下。
1 ,nginx 设置 header 搜索下很容易找到这样的例子 proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; 但对自定义的头怎么取 就没什么例子了 经过反复摸索 发现nginx要取自定义的变量是这样的 $http_自定义header名 这里要注意 header名要都转成小写 中划线改成下划线 比如我们的 True-Client-IP 到nginx里 用 $http_true_client_ip就可以接收到了 proxy_set_header Remote_Addr $http_true_client_ip;
2. 因为不是所有的域名都加速了 所有有的请求是有 True-Client-IP 有的没有 ,nginx要判断下 ,没有那个头的 就转发remote_addr到后台 开始我是这么写的 if($http_true_client_ip != ''){ proxy_set_header Remote_Addr $http_true_client_ip; } 会报 "proxy_set_header" directive is not allowed here 这个错误 G之 在 http://www.pubbs.net/200908/nginx/14399-possible-to-normalize-headers-in-nginx.html 得到方法 ,proxy_set_header 不能在if里 但 if里可以set变量 最终配置写法: if ($http_true_client_ip != ''){ set $clientip $http_true_client_ip; break; } if ($http_true_client_ip = ''){ set $clientip $remote_addr; break; } proxy_set_header Remote_Addr $clientip;
注意: if 和 ( 之间一定要有空格
BTW://中文的资料就那一两篇文章转来转去...哎
1 ,nginx 设置 header 搜索下很容易找到这样的例子 proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; 但对自定义的头怎么取 就没什么例子了 经过反复摸索 发现nginx要取自定义的变量是这样的 $http_自定义header名 这里要注意 header名要都转成小写 中划线改成下划线 比如我们的 True-Client-IP 到nginx里 用 $http_true_client_ip就可以接收到了 proxy_set_header Remote_Addr $http_true_client_ip;
2. 因为不是所有的域名都加速了 所有有的请求是有 True-Client-IP 有的没有 ,nginx要判断下 ,没有那个头的 就转发remote_addr到后台 开始我是这么写的 if($http_true_client_ip != ''){ proxy_set_header Remote_Addr $http_true_client_ip; } 会报 "proxy_set_header" directive is not allowed here 这个错误 G之 在 http://www.pubbs.net/200908/nginx/14399-possible-to-normalize-headers-in-nginx.html 得到方法 ,proxy_set_header 不能在if里 但 if里可以set变量 最终配置写法: if ($http_true_client_ip != ''){ set $clientip $http_true_client_ip; break; } if ($http_true_client_ip = ''){ set $clientip $remote_addr; break; } proxy_set_header Remote_Addr $clientip;
注意: if 和 ( 之间一定要有空格
BTW://中文的资料就那一两篇文章转来转去...哎
相关阅读 更多 +