目标:
利用nginx实现server_ip:8080 代理 server_ip:8000
获取真实的访问者IP
1. 修改nginx配置文件
在location ~ {}的大括号内添加如下参数
proxy_set_header Host $host:8080;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
2. flask代码
将request.remote_addr修改为request.headers['X-Real-Ip']
@flask_login.user_logged_in.connect_via(app)
def _track_logins(sender, user, **extra):
user.login_count += 1
#user.login_ip = request.remote_addr
user.login_ip = request.headers['X-Real-Ip']
db.session.add(user)
db.session.commit()
3. 可以尝试查看请求headers头信息
在flask代码中添加print request.headers
X-Real-Ip: 10.0.1.166
Content-Length:
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:50.0) Gecko/20100101 Firefox/50.0
Connection: Keep-Alive
Remote-Host: 10.0.1.166
Host: 172.16.3.9
Upgrade-Insecure-Requests: 1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Proxy-Connection: Keep-Alive
Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3
X-Forwarded-For: 10.0.1.166
Content-Type:
Accept-Encoding: gzip, deflate
4. 完整nginx配置文件
events
{
worker_connections 1024;
}
http{
client_max_body_size 100m;
proxy_cache_path /tmp/threat levels=1:2 keys_zone=cache1:80m max_size=10000m inactive=60000m;
server_tokens off;
upstream backserver {
server 127.0.0.1:8080;
keepalive 15;
}
log_format proxy_combined '$remote_addr [$time_local] "$request" $status $body_bytes_sent $request_time "$upstream_cache_status"';
log_format timed_combined '$http_x_forwarded_for $remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time $pipe';
server {
listen 8080;
client_body_buffer_size 128k;
proxy_connect_timeout 600;
proxy_read_timeout 600;
proxy_send_timeout 6000;
add_header X-Cache $upstream_cache_status;
#不缓存/login页面
location =/login{
proxy_pass http://127.0.0.1:8000;
proxy_http_version 1.1;
#proxy_set_header Connection "Keep-Alive";
#proxy_set_header Proxy-Connection "Keep-Alive";
access_log /var/log/nginx/proxy_access.log proxy_combined;
proxy_set_header Host $host:8080;
proxy_set_header X-Real-Ip $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location ~ {
proxy_cache cache1;
proxy_cache_valid 200 302 5d;
proxy_cache_methods GET HEAD POST;
proxy_cache_key "$request_uri|$request_body";
#只缓存当前访问IP访问过的页面,其他IP访问该页面不缓存
#proxy_cache_key "$remote_addr|$request_uri|$request_body";
proxy_pass http://127.0.0.1:8000;
proxy_http_version 1.1;
#proxy_set_header Connection "Keep-Alive";
#proxy_set_header Proxy-Connection "Keep-Alive";
access_log /var/log/nginx/proxy_access.log proxy_combined;
proxy_set_header Host $host:8080;
proxy_set_header X-Real-Ip $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}