博客目前跑在国际版AWS的EC2上面,然而国际版AWS对大陆并不友好的网络也是众所周知的,为了保证博客的访问速度,趁着打折,败了一台C3机房的小鸡(vps)来做反向代理。然而问题就出现了。经过反代之后,Wordpress里面那些需要收集用户ip的地方,例如SlimStat和部分反垃圾评论的插件,收集到的访问者的ip都会变成反代前端那台小鸡的ip。这样会影响很多插件的正常工作。
经过一番谷歌,发现解决问题的思路并不复杂。首先,反代前后端的web server组件都是用的nginx,nginx有http_realip_module这个模块,这个模块可以让前端的nginx在反向代理的时候通过一个header把用户的真实ip传递给后端的服务器。后端的网站程序只要从这个header来读取用户的ip地址,即可获得用户的真实ip,而不是反代前端服务器的ip地址。
首先,检查你的nginx有没有编译http_realip_module这个模块,命令如下:
[root@VPS ~]# nginx -V nginx version: nginx/1.10.2 built by gcc 4.4.7 20120313 (Red Hat 4.4.7-17) (GCC) built with LibreSSL 2.4.4 TLS SNI support enabled configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-http_ssl_module --with-http_realip_module --with-http_addition_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_stub_status_module --with-http_auth_request_module --with-http_xslt_module=dynamic --with-http_image_filter_module=dynamic --with-http_geoip_module=dynamic --with-threads --with-stream --with-stream_ssl_module --with-http_slice_module --with-mail --with-mail_ssl_module --with-file-aio --with-ipv6 --with-http_v2_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic' --with-openssl=/root/nginx-source/libressl/libressl-2.4.4 --with-pcre=/root/nginx-source/pcre/pcre-8.39 --with-ld-opt=-lrt
如果能看到有–with-http_realip_module这个参数,说明realip模块已经编译进去了。如果没有,需要重新编译nginx,具体教程可以参考我之前发的文章。
然后,需要在反代前端的nginx配置文件里面启用这个功能,下面是一个示例
location / { #root html; #index index.html index.htm; proxy_pass https://12.34.56.78:443; proxy_redirect off; proxy_set_header Host $host; #这行打开real-ip这个header proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; }
最后就是对网站程序的设置了。对于wordpress程序来说,只要把如下一段代码添加到网站根目录下面的wp-config.php文件的最前面即可。
if (isset($_SERVER['HTTP_X_REAL_IP'])) { $_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_X_REAL_IP']; }
保存之后,效果是立竿见影的,SlimStat直接采集到了访问者的真实ip,评论管理界面也能看到评论者的真实ip了。
在 “反代后端的wordpress识别访问者的真实ip” 上有 1 条评论