轉自:http://blog.csdn.net/vaal_water/article/details/6004372
公司的網站要加入動態加速 一個直接的問題是經過轉發 客戶端請求的頭被改了一部分 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://中文的資料就那一兩篇文章轉來轉去...哎
PS : APACHE不能直接得到轉發的IP php里用getallheaders() 看到頭其實是打過來了 但 $_SERVER里 變成了
http_remote_addr 要直接得到真實IP 需要apache上安裝個mod mod_rpaf
apache的第三方的mod
最 新版本是 mod_rpaf-0.6.tar.gz