nginx通过http_x_forwarded_for限制来访IP示例
由于入访经过负载均衡设备,后端nginx无法获取client_ip,只能通过http_x_forwarded_for获取到最原始用户IP。这里通过http_x_forwarded_for来限制固定IP的用户可以访问。
普通client_ip限制方法
#反向代理地址
upstream sandbox-open {
server 10.10.10.5:8080;
}
#30001对外端口
server {
listen 30001;
server_name sandbox.open.com;
access_log /var/log/nginx/sandbox-open_access.log;
client_max_body_size 20m;
location / {
# 仅允许如下client_ip访问
allow 10.10.10.12;
allow 10.10.11.12/24;
deny all;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://sandbox-open;
proxy_redirect off;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
http_x_forwarded_for限制方法1(推荐)
#http_x_forwarded_for地址不在下列IP中则返回403
map accessip {
default false;
#10.10.10.10(IP匹配)
10.10.10.10 true;
10.10.10.11 true;
10.10.10.12 true;
#10.10.50.0/24(网段匹配)
~*10.10.50. true;
}
#反向代理地址
upstream sandbox-open {
server 10.10.10.5:8080;
}
#30001对外端口
server {
listen 30001;
server_name sandbox.open.com;
access_log /var/log/nginx/sandbox-open_access.log;
client_max_body_size 20m;
location / {
#http_x_forwarded_for地址不在下列IP中则返回403
if ( $accessip = 'false') {return 403;}
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://sandbox-open;
proxy_redirect off;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
http_x_forwarded_for限制方法2
#反向代理地址
upstream sandbox-open {
server 10.10.10.5:8080;
}
#30001对外端口
server {
listen 30001;
server_name sandbox.open.com;
access_log /var/log/nginx/sandbox-open_access.log;
client_max_body_size 20m;
location / {
#http_x_forwarded_for地址不在下列IP中则返回403
set http_x_forwarded_for = '10.10.10.10' ) {set http_x_forwarded_for = '10.10.10.11' ) {set http_x_forwarded_for = '10.10.10.12' ) {set http_x_forwarded_for = '192.168.1.1' ) {set accessip = 'false') {return 403;}
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host remote_addr;
proxy_set_header X-Forwarded-For http_x_forwarded_for = ‘~*10.10.50.’ ) {set $accessip true;}
————————————————
版权声明:本文为CSDN博主「skywin88」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Skywin88/article/details/117983840
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了