直奔主題,在代理伺服器的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`]。