Nginx 在 Debian 上的访问控制策略
一 网络层与主机层控制
sudo ufw allow from 192.168.1.1 to any port 80,sudo ufw default deny incoming,sudo ufw enable。也可直接限制端口:sudo ufw deny 80(注意避免把自己锁在外面)。二 应用层控制
location /admin {
allow 192.168.1.0/24;
deny all;
}
sudo apt-get install apache2-utils;创建密码文件 sudo htpasswd -c /etc/nginx/.htpasswd username;在配置中启用:location / {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
}
location / {
if ($http_x_custom_header = "allowed_value") { allow all; }
deny all;
}
location / {
auth_request /auth;
}
location = /auth {
internal;
proxy_pass http://auth-service/validate;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header X-Original-URI $request_uri;
}
提示:部分发行版需要安装包含该模块的包(如 nginx-extras)或通过源码编译启用。三 TLS 客户端证书认证
server {
listen 443 ssl;
server_name yourdomain.com;
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
ssl_client_certificate /etc/ssl/certs/ca-certificates.crt;
ssl_verify_client on;
location / {
root /var/www/html;
index index.html;
}
}
说明:将 /etc/ssl/certs/ca-certificates.crt 替换为你的 CA 证书 路径。四 速率与并发限制
http {
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
location / {
limit_conn addr 100; # 每个IP最多100个并发连接
# 可按需增加 limit_req 限制请求速率
}
}
}
提示:结合业务场景设置合理阈值,避免影响正常用户。五 部署与运维要点
sudo nginx -t && sudo systemctl reload nginx。