Nginx反向代理后端RS记录客户端真实ip
负载均衡服务器的配置
[root@KEEP1 conf]# cat nginx.conf
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
upstream web_real_server{
# ip_hash; #用ip哈希算法保持会话
server 10.0.0.3:80 max_fails=3 fail_timeout=20s;
server 10.0.0.4:80 max_fails=3 fail_timeout=20s;
}
server {
listen 80;
server_name www.lvnian.com;
location / {
index index.php index.htm index.html;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_next_upstream http_500 http_502 http_503 error timeout invalid_header;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://web_real_server;
}
}
}
[root@KEEP1 conf]#
proxy_pass http://web_real_server;
用于指定反向代理的服务器池
proxy_set_header Host $host;
当后端web服务器上也配置有多个虚拟主机时,需要用该Header来区分反向代理那个主机名。在每个server模块中设置,区分每个虚拟主机。
proxy_set_header X-Forwarded-For $remote_addr;
如果后端Web服务器上的程序需要获取用户IP,从该Header头中获取
proxy_next_upstream http_500 http_502 http_503 error timeout invalid_header;
这个参数是用来定义故障转移策略的,当后端服务器节点返回500/502/503和执行超时等错误时,自动将请求转到upstream负载均衡中的另外一台服务器,实现故障转移
=========================================================================
后端RS服务器的配置文件
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name www.lvnian.com;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
#########
set_real_ip_from 10.0.0.0/24;
real_ip_header X-Forwarded-For;
######这两个参数是记录真实IP的
}
}
########################################
日志格式(默认即可):
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
#其中最主要的是: $remote_addr 和 "$http_x_forwarded_for"
################################################################################
如果RS是Aapche服务,默认情况下仅仅需要改变日志格式就可以记录客户端的真实IP
Apache的日志格式改为如下格式:
LogFormat " \"%{X-Forwarded-For}i\ %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
主要的就是 \"%{X-Forwarded-For}i\ 这个参数记录了真实客户端的IP地址