Skip to content

Nginx 访问认证

基于用户的登录访问

Nginx 支持通过 HTTP Basic Authentication 对特定目录或服务进行访问控制,要求用户输入用户名和密码才能访问资源。

安装依赖工具

bash
# Ubuntu/Debian
sudo apt-get -y install apache2-utils

# CentOS/RHEL
dnf -y install httpd-tools

创建密码文件

bash
htpasswd -bc /usr/local/nginx/conf/htpasswd username passwd

Nginx 配置

nginx
server {
    listen 80;
    server_name example.com;

    location /protected/ {
        auth_basic "Restricted Area";      					  # 认证提示语
        auth_basic_user_file /usr/local/nginx/conf/htpasswd;  # 密码文件路径
        
        # 限制尝试次数
    	limit_req zone=auth burst=3 nodelay;
    }
}
# 防止暴力破解
http {
    limit_req_zone $binary_remote_addr zone=auth:10m rate=1r/s;
}

Nginx 黑白名单配置

IP 黑白名单(基于 allow/deny

基础配置

nginx
http {
    # 定义黑名单(全局生效)
    deny 192.168.1.100;          # 封禁单个IP
    deny 10.0.0.0/24;            # 封禁整个子网
    allow all;                   # 允许其他所有IP
    # 使用单独的黑名单文件
    include /etc/nginx/blockips.conf
}

server {
    listen 80;
    server_name example.com;

    location /admin/ {
        # 白名单(仅允许指定IP)
        allow 203.0.113.5;
        allow 172.16.0.0/16;
        deny all;                # 拒绝其他所有IP
    }
}
  • 生效顺序:规则按从上到下匹配,第一条匹配的规则生效

  • blockips.conf

    ini
    deny 1.2.3.4;
    deny 5.6.7.8;

动态黑名单(结合 geo 模块)

nginx
http {
    # 定义IP分类
    geo $blocked_ip {
        default 0;
        192.168.1.100 1;    # 黑名单IP
        10.0.1.0/24    1;    # 黑名单子网
    }

    server {
        if ($blocked_ip) {
            return 403 "Forbidden";
        }
    }
}

国家/IP段封禁

需要编译ngx_http_geoip_module

nginx
http {
    geoip_country /usr/share/GeoIP/GeoIP.dat;
    map $geoip_country_code $allowed_country {
        default yes;
        CN no;       # 封禁中国IP
        RU no;       # 封禁俄罗斯IP
    }

    server {
        if ($allowed_country = no) {
            return 403 "Region Blocked";
        }
    }
}

基于 HTTP 头部的访问控制

禁止特定 User-Agent

nginx
map $http_user_agent $bad_bot {
    default 0;
    ~*(curl|wget|python) 1;  # 屏蔽爬虫工具
}

server {
    if ($bad_bot) {
        return 403 "Bot Not Allowed";
    }
}

限制 Referer 防盗链

nginx
location ~* \.(jpg|png|mp4)$ {
    valid_referers none blocked example.com *.example.org;
    
    if ($invalid_referer) {
        return 403 "Hotlinking Forbidden";
    }
}