Nginx代理後服務端使用remote_addr獲取真實IP

直奔主題,在代理服務器的Nginx配置(yourWebsite.conf)的location /中添加:

#獲取客戶端IP
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For 
$proxy_add_x_forwarded_for;

在業務服務器的Nginx配置(yourWebsite.conf)的location中添加:

fastcgi_param  HTTP_X_FORWARDED_FOR $http_x_forwarded_for;

配置到這,可以用HTTP_X_FORWARDED_FOR獲取客戶端真實IP,以PHP爲例,$_SERVER['HTTP_X_FORWARDED_FOR'],但是remote_addr還是代理服務器的IP,接着往下配置,把remote_addr也配置成真實IP。

在業務服務器的Nginx配置(yourWebsite.conf)的location中繼續添加:

set_real_ip_from 172.18.209.11/24;#這裏的IP是代理服務器的IP,也可以是IP段。意思是把該IP請求過來的x_forwarded_for設爲remote_addr
real_ip_header X-Forwarded-For;

Tip:添加上面兩行之前,需要查看Nginx是否安裝了realip模塊,Nginx默認是不安裝的,查看命令 nginx -V ,結果如下所示,如果沒有realip模塊,需要先安裝。

 

nginx version: nginx/1.14.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-28) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --with-select_module --with-poll_module --with-threads --with-file-aio --with-http_ssl_module --with-http_realip_module --with-http_addition_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_auth_request_module --with-http_random_index_module --with-http_degradation_module --with-http_slice_module --with-http_stub_status_module --with-stream --with-stream=dynamic --with-stream_ssl_module --with-pcre --add-module=/usr/local/nginx_upstream_check_module-master/

 

 

至此就可以使用remote_addr獲取客戶端的真實地址,如PHP的$_SERVER['remote_addr']。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章