Nginx如何保留真實IP和獲取前端IP


原理:
squid,varnish以及nginx等,在做反向代理的時候,因為要代替客戶端去訪問服務器,所以,當請求包經過反向代理后,在代理服務器這里這個IP數據包的IP包頭做了修改,最終后端web服務器得到的數據包的頭部的源IP地址是代理服務器的IP地址,這樣一來,后端服務器的程序給予IP的統計功能就沒有任何意義,所以在做代理或集群的時候必須解決這個問題,這里,我以nginx做集群或代理的時候如何給后端web服務器保留(確切的說是傳遞)客戶端的真實IP地址。
nginx實用X-Forwarded-For這個參數來解決這個問題我們用幾個實例來解決
-----------------------------------------------------------------------------------------------------------
nginx+tomcat實例
1,nginx配置文件設置如下

upstream tomcat_server
  {
  server 192.168.1.66:8080;
  }
  server
  {
    listen       80;
    server_name  node1.113d.com;
    index index.html index.htm index.jsp default.jsp index.do default.do;
    root  /home/www/game;
    error_page 404 = http://game1.113d.com;
if (-d $request_filename)
{
        rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
}

#轉發動態頁面給Tomcat處理
location ~ \.(jsp|jspx|do)?$ {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://tomcat_server;
2,tomcat應用工程(網站程序配置)
用 String ip = request.getHeader("X-Real-IP");替代String ip = request.getRemoteAddr();
這是程序這款的了
-----------------------------------------------------------------------------------------------------------
apache+nginx靜態和動態分離,nginx在apache前,做的PROXY來轉發請求到內部的apache上
1,nginx配置:
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

2,apache配置:
用mod_rpaf來獲取IP的
所以需要安裝這個模塊
下載: http://stderr.net/apache/rpaf/download/
tar zxvf mod_rpaf-0.6.tar.gz
cd mod_rpaf-0.6
/usr/local/www/apache/bin/apxs -i -c -n mod_rpaf-2.0.so mod_rpaf-2.0.c
配置apache:
在 httpd.conf中添加
LoadModule rpaf_module libexec/apache2/mod_rpaf-2.0.so
RPAFenable On
RPAFsethostname On
RPAFproxy_ips 192.168.1.1 #這個是前段的IP,可不是后端的IP哦
RPAFheader X-Forwarded-For

注意,不僅僅要配置nginx,后端獲取也需要做配置,例如上面兩個例子都做了相應的配置
-----------------------------------------------------------------------------------------------------------
nginx+nginx或squid+nginx,也就是說nginx是后端的web服務器,前端用nginx或squid做了緩存服務器,那么nginx如何接受的呢,這里注意了,nginx既可以給后端保留真實IP,也可以作為后端服務器接受前端給的真實IP,他是如何接受的你
nginx通過http_realip_module模塊來實現的
這需要重新編譯,如果提前編譯好了就無需重新編譯了
1,重新編譯nginx
編譯
./configure --user=www --group=www --prefix=/usr/local/webserver/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_realip_module
make
make install

配置
set_real_ip_from   192.168.1.0/24;     指定接收來自哪個前端發送的 IP head 可以是單個IP或者IP段
set_real_ip_from   192.168.2.1;
real_ip_header     X-Real-IP;                  IP head 的對應參數,默認即可。
加載
./nginx -s reload
我們看到nginx的http_realip_module模塊和apache的第三方模塊mod_rpaf的作用是一樣的
千萬注意:nginx的http_realip_module和前面的proxy_set_header 是不同的
proxy_set_header:是給后端服務器保留真實IP
http_realip_module:是獲取別人給nginx保留的真實IP
總之: 
1,前段要配置保留
2,后端要配置接受


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM