實現反向代理客戶端IP透傳
阿新 • • 發佈:2022-01-16
預設情況下,使用反向代理時,後端伺服器只能看到訪問是從反向代理伺服器的IP,無法真正識別到客戶端IP。通過配置IP透傳實現後端伺服器識別到客戶端真實IP。
一、Apache後端伺服器部署
1.1 安裝apaceh
[root@web ~]# yum -y install httpd
1.2 修改配置檔案
[root@web ~]# vim /etc/httpd/conf/httpd.conf ...省略 LogFormat "%{X-Forwarded-For}i %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"% #在此項新增%{X-Forwarded-For}i
1.3 啟動apache
[root@web ~]# systemctl start httpd
二、安裝反向代理
2.1 安裝nginx
[root@nginx ~]# yum -y install nginx
2.2 修改配置檔案
[root@nginx ~]# vim /etc/nginx/nginx.conf user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; include /etc/nginx/conf.d/*.conf; server { listen 80; root /usr/share/nginx/html; include /etc/nginx/default.d/*.conf; location / { index index.html index.php; root /data/nginx/html/pc; proxy_pass http://10.0.0.18; #新增此項 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #新增此項 } } }
2.3 啟動nginx
[root@nginx ~]# systemctl start nginx
三、測試IP透傳
#開啟客戶端瀏覽器訪問10.0.0.8,然後觀察後端伺服器日記 [root@web ~]#tail /var/log/httpd/access_log ...省略... 10.0.0.3 10.0.0.8 - - [16/Jan/2022:14:11:31 +0800] "GET /favicon.ico HTTP/1.0" 404 196 "http://10.0.0.8/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36" 10.0.0.3 10.0.0.8 - - [16/Jan/2022:14:11:33 +0800] "GET / HTTP/1.0" 304 - "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36"