2016-07-31 60 views
2

我安裝了nginx,php7和http_realip_module。nginx實際客戶端ip不能正常工作

我有1個服務器,服務2個網站。

網站1個nginx的配置:

server { 
    ... 
    location ~ \.php$ { 
     include snippets/fastcgi-php.conf; 
     fastcgi_pass unix:/run/php/php7.0-fpm.sock; 
     fastcgi_read_timeout 300; 

     proxy_set_header REMOTE_ADDR $http_x_real_ip; 
     proxy_set_header X-Forwarded-For $http_x_real_ip; 
    } 
} 

當我傾倒$ _ SERVER ['REMOTE_ADDR「]

網站1使用curl像一個簡單的API連接到站點2此填入客戶端的IP地址。

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string); 
curl_setopt($ch, CURLOPT_URL, $serverUrl); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "REMOTE_ADDR: ".$_SERVER['REMOTE_ADDR'], 
    "HTTP_X_FORWARDED_FOR: ".$_SERVER['REMOTE_ADDR'], 
)); 
$result = curl_exec($ch); 

網站2 nginx的配置:

server { 
    ... 
    location ~ \.php$ { 
     include snippets/fastcgi-php.conf; 
     fastcgi_pass unix:/run/php/php7.0-fpm.sock; 
     fastcgi_read_timeout 300; 

     set_real_ip_from 127.0.0.1; 
     real_ip_header X-Forwarded-For; 
     real_ip_recursive on; 

    } 
} 

我可以看到站點2上的腳本被調用,但是當我檢查PHP中的$ _SERVER ['REMOTE_ADDR']變量時,它提供了服務器的IP地址,而不是客戶端的IP地址。這裏的nginx設置是否正確?

我怎樣才能使這個工作正常?

回答

2

經過一番討論和下面的一些試驗/錯誤,我們發現最好的解決方案是簡單地通過$_GET參數。

嘗試使用一個完全自定義標題:

curl_setopt($ch, CURLOPT_URL, $serverUrl . '?client_ip=' . $_SERVER['REMOTE_ADDR']); 

因爲你只是轉發此變量,它是不是真的有必要去嘗試,它裁縫頭。

經過進一步的討論,我發現nginx strips headers with underscores by default。簡單地將下劃線改爲破折號允許最終主機得到標題:

curl_setopt($ch, CURLOPT_HTTPHEADER, array( 
    "X-CLIENT-REMOTE-IP: " . $_SERVER['REMOTE_ADDR'] 
)); 
+0

似乎沒有工作?當我進一步看捲曲時,它看起來並沒有將標題發送到site2 php頁面。 $ _SERVER變量是否包含X_CLIENT_REMOTE_IP變量? – Ourx

+0

您是否嘗試過只是在執行'print_r($ _ SERVER);'? – FrankerZ

+0

錯字:$ _SERVER變量-doesnt-包含X_CLIENT_REMOTE_IP變量 – Ourx

相關問題