Nginx獲取用戶真實IP


Nginx獲取用戶真實IP地址

本人在一次項目中,使用Nginx需要獲取到用戶IP,本來可以很常規的獲取的,可現實往往不常規,項目是前后端分離的,部署時,前端使用了Nginx進行了代理並轉發,后端也使用了Nginx進行了負載均衡和代理,分別部署在兩台機器上,使用的不是同一個Nginx,所以此處當用戶的請求過來時,先是通過前端Nginx轉發到后端Nginx,后端Nginx再轉發到具體的服務上,當時使用常規手法獲取IP,結果獲取到的是前端部署的機器IP。

在此本人通過了Nginx的realip模塊進行了獲取,特此來記錄一下。

使用Nginx自帶模塊realip模塊獲取IP地址

首先來看看配置文件,此處只展示主要部分

http {
    include       mime.types;
    default_type  application/octet-stream;

    #access_log  logs/access.log  main;
	access_log off;
    error_log off;
    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;
	#負載均衡配置 
    upstream serverCluster{
        server 127.0.0.1:82 weight=1;
        server 192.168.0.80:81 weight=1;
    }
	
    server {
        listen       80; #監聽的端口
        server_name  yunque.natapp1.cc;
        
        #配置負載均衡
        location /{
            proxy_next_upstream http_502 http_504 error timeout invalid_header;
            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://serverCluster;
			set_real_ip_from  192.168.1.0/254;
			real_ip_header X-Real-IP;
			real_ip_recursive on;
            expires   3d;
        }
    }

}

set_real_ip_from  127.0.0.1; #這一網段過來的請求全部使用X-Real-IP里的頭信息作為remote_addr
real_ip_header X-Real-IP;#從哪個header頭檢索出所要的IP地址
real_ip_recursive on; #開啟

接下來就是測試配置是否正確

# 在Nginx安裝目錄下輸入一下命令
./sbin/nginx -tc conf/nginx.conf

如果報一下錯:

說第66行是未知的命令,表示當前Nginx沒有相關realip模塊,所以缺少該模塊相關命令

下載realip模塊並進行配置

 找到Nginx解壓的目錄,在該目錄下輸入以下命令

# 下載http_realip_module模塊
./configure --prefix=/usr/local/nginx-1.4.1 --with-http_realip_module --原來有的模塊(如果有的話)
# 查看Nginx版本號 (/usr/local/nginx/是你Nginx服務器的實際位置)
/usr/local/nginx/sbin/nginx -V

查看configure arguments:后邊有沒有值,如果有,就復制下來。

 配置完成后,運行命令make命令

make
# 注意,此處不能mark install 否則就是覆蓋安裝

替換已安裝好的Nginx包

 替換之前先備份:

cp /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.bak

先停止Nginx服務 

# 停止服務
./usr/local/nginx/sbin/nginx -s stop

將剛剛編譯好的nginx覆蓋掉原有的nginx 

# 在Nginx解壓目錄下使用以下命令
cp ./objs/nginx /usr/local/nginx/sbin/

# 通過查看版本命令收看是否下載SSL模塊成功
/usr/local/nginx/sbin/nginx -V

啟動服務即可,命令如下

./usr/local/nginx/sbin/nginx


免責聲明!

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



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