Nginx作为反向代理服务器时,可以通过配置实现对多端口的精细化访问控制。这种策略常用于以下场景: - 不同服务通过不同端口暴露 - 需要基于端口实施不同的安全策略 - 多租户环境下的端口隔离
server {
listen 8080;
server_name example.com;
location / {
allow 192.168.1.0/24;
deny all;
proxy_pass http://backend_server;
}
}
server {
listen 8081;
server_name example.com;
location / {
allow 10.0.0.0/8;
deny all;
proxy_pass http://another_backend;
}
}
geo $allowed_port8080 {
default 0;
192.168.1.0/24 1;
10.0.0.1 1;
}
geo $allowed_port8081 {
default 0;
10.0.0.0/8 1;
}
server {
listen 8080;
if ($allowed_port8080 = 0) {
return 403;
}
proxy_pass http://backend8080;
}
server {
listen 8081;
if ($allowed_port8081 = 0) {
return 403;
}
proxy_pass http://backend8081;
}
map $remote_addr $port_access {
default "deny";
192.168.1.100 "allow:8080,8081";
10.0.0.5 "allow:8080";
}
server {
listen 8080;
set $check_port "8080";
if ($port_access !~ "allow:$check_port") {
return 403;
}
proxy_pass http://backend8080;
}
server {
listen 8081;
set $check_port "8081";
if ($port_access !~ "allow:$check_port") {
return 403;
}
proxy_pass http://backend8081;
}
map $time_iso8601 $working_hours {
default 0;
"~^(\d{4}-\d{2}-\d{2}T(0[8-9]|1[0-7]):)" 1;
}
server {
listen 8080;
if ($working_hours = 0) {
return 403;
}
proxy_pass http://business_hours_backend;
}
server {
listen 8081;
# 24/7访问
proxy_pass http://always_on_backend;
}
server {
listen 8080;
access_by_lua_block {
local ip = ngx.var.remote_addr
local port = ngx.var.server_port
-- 调用外部API或查询数据库检查权限
local res = ngx.location.capture("/check_access?ip="..ip.."&port="..port)
if res.status ~= 200 then
ngx.exit(ngx.HTTP_FORBIDDEN)
end
}
proxy_pass http://dynamic_backend;
}
日志记录:记录所有端口访问尝试
log_format port_access '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" $server_port';
access_log /var/log/nginx/port_access.log port_access;
通过以上策略,可以实现灵活、安全的Nginx多端口访问控制,满足不同业务场景的需求。