一、前言
在实际业务开发过程中,很多时候有记录客户端真实IP的需求,但是从客户端发送的请求往往会经过很多代理服务器,导致后端服务获取的IP为代理以后的IP,不具有业务含义。为了解决这个问题,可以搭建一个旁路服务器,前端在发起请求的时候需要先请求旁路服务器,获取该客户端的真实IP(可对该IP地址进行缓存,不必每次发送请求前都先请求旁路服务器),在真正向后端发送请求时,将获取的IP地址放入X-Forwarded-For请求头中,将真实的客户端IP地址进行传递。
二、解决方案
使用Nginx搭建旁路服务器,客户端向后端发送请求时,先请求一次Nginx服务器,返回真实的客户端IP(可将该IP进行缓存,减少旁路服务器请求),在真正向后端发送请求时,将获取的IP地址放入X-Forwarded-For请求头中,将真实的客户端IP地址进行传递。
2.1 搭建http协议旁路服务器
1、修改Nginx的nginx.conf配置文件,添加返回IP地址的代码:
server {listen 80;server_name localhost;location / {root html;index index.html index.htm;}# 添加返回文本格式的IP地址映射,返回请求方IPlocation /http_ip {default_type text/plain;return 200 $remote_addr;}# 添加返回json格式的IP地址映射,返回请求方IPlocation /http_json_ip {default_type application/json;return 200 "{\"ip\":\"$remote_addr\"}";}#error_page 404 /404.html;# redirect server error pages to the static page /50x.html#error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}}
2、启动Nginx
3、进行请求测试
• 文本格式:
• JSON格式:
2.2 搭建https协议旁路服务器
1、生成https证书
(1)下载openssl:
https://slproweb.com/products/Win32OpenSSL.html
(2) 安装openssl,按照提示【下一步】就行
(3) 创建私钥,进入到安装目录的bin目录下,在此目录下打开CMD命令窗口,然后执行:
openssl genrsa -des3 -out nginx-https.key 1024
执行过程中需要设置密码,随便设置一个就行:
执行完成以后,会生成私钥文件:
(4) 为了后续启动nginx不输入密码,可以多做一步删除密码的操作,在CMD窗口执行:
openssl rsa -in nginx-https.key -out nginx-https.key.unsecure
(5) 创建 csr 证书同样在openssl安装bin目录下,在CMD窗口执行:
openssl req -new -key nginx-https.key.unsecure -out nginx-https.csr
执行过程中需要输入一些信息,随便输入就行,最后会生成一个csr文件。
(6) 生成crt证书:
openssl x509 -req -days 365 -in nginx-https.csr -signkey nginx-https.key.unsecure -out nginx-https.crt
(7) 最终生成文件:
2、 修改nginx启动配置
# HTTPS serverserver {listen 443 ssl;server_name localhost;# 这个是证书的crt文件所在目录ssl_certificate D:/devTools/openssl/service/bin/nginx-https.crt;# 这个是证书key文件所在目录ssl_certificate_key D:/devTools/openssl/service/bin/nginx-https.key.unsecure;ssl_session_cache shared:SSL:1m;ssl_session_timeout 5m;ssl_ciphers HIGH:!aNULL:!MD5;ssl_prefer_server_ciphers on;location / {root html;index index.html index.htm;}# 添加返回文本格式的IP地址映射location /http_ip {default_type text/plain;return 200 $remote_addr;}# 添加返回json格式的IP地址映射location /http_json_ip {default_type application/json;return 200 "{\"ip\":\"$remote_addr\"}";}}
3 、启动Nginx
4 、进行请求测试
• 文本格式
• JSON格式
到此使用Nginx搭建旁路服务器就完成了。
三、注意
使用Nginx搭建旁路服务器虽然可以获取到客户端真实的IP,但是有一个问题,通信过程中请求头可能被第三方篡改,导致获取IP也并非真实IP,这个需要特别留意。
原创 Coder文小白