nginx默認配置文件里面是沒有進行日志轉發配置的,這個需要我們自己手動來操作了,當然后端的real server不同時操作方法是不一樣的,這里我們分別例舉幾種情況來說明一下。
nginx做前端,轉發日志到后端nginx服務器:
因為架構的需要采用多級 Nginx 反向代理,但是后端的程序獲取到的客戶端 IP 都是前端 Nginx 的 IP,問題的根源在于后端的 Nginx 在 HTTP Header 中取客戶端 IP 時沒有取對正確的值。
同樣適用于前端是 Squid 或者其他反向代理的情況。
首先前端的 Nginx 要做轉發客戶端 IP 的配置:
location / {proxy_pass http://localhost:8000; # Forward the user's IP address to Railsproxy_set_header X-Real-IP $remote_addr;# needed for HTTPS# proxy_set_header X_FORWARDED_PROTO https;proxy_set_header X-Forwarded-For $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header Host $host;proxy_redirect off;}
后端的 Nginx 需要安裝一個 Module: NginxHttpRealIpModule,編譯的時候默認不包含此 Module,需要重新編譯安裝 Nginx,configure 的時候加上 –with-http_realip_module,Nginx 升級或者添加/刪除 Module 時支持熱切換,可以避免中斷服務。
升級后配置 NginxHttpRealIpModule,set_real_ip_from 就是指前端 Nginx 或者 Squid 的 IP:
location / {proxy_pass http://localhost:8000; # Forward the user's IP address to Railsproxy_set_header X-Real-IP $remote_addr;# needed for HTTPS# proxy_set_header X_FORWARDED_PROTO https;proxy_set_header X-Forwarded-For $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header Host $host;proxy_redirect off;# NginxHttpRealIpModuleset_real_ip_from 192.168.1.0/24;set_real_ip_from 192.168.2.1;real_ip_header X-Real-IP;}
最后記得 reload Nginx config
nginx做前端,轉發日志到后端apache服務器:
apache日志中默認有%h來指定來訪客戶端你的ip地址,但是使用了nginx代理上網則%h獲得的ip地址會不準。
這就需要對nginx 和apache的配置文件設定 X-Forwarded-For 參數來獲取客戶端真實的ip地址。對于使用了反向代理的客戶端,跟蹤真實的ip地址。
/usr/nginx/conf/nginx.conf 添加以下參數:
proxy_set_header Host $host;proxy_set_header X-Forwarded-For $remote_addr;proxy_set_header X-Forwarded-Host $server_name;proxy_set_header X-Real-IP $remote_addr;
同時修改:
server { listen 80; server_name 域名 ; proxy_redirect off; location / { proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header Host $host; proxy_pass http://域名; } access_log off; }
重啟nginx使配置生效。
apache端需要安裝一個第三方模塊"mod_rpaf"了, 官方網站: http://stderr.net/apache/rpaf/
新聞熱點
疑難解答