插件窝 干货文章 nginx如何设置目录白名单和ip白名单

nginx如何设置目录白名单和ip白名单

Nginx 名单 server allow 540    来源:    2025-04-23

Nginx 设置目录白名单和IP白名单

Nginx可以通过多种方式实现访问控制,包括目录白名单和IP白名单。以下是详细的配置方法:

目录白名单设置

1. 使用 location 指令限制目录访问

server {
    listen 80;
    server_name example.com;

    # 允许所有人访问根目录
    location / {
        root /var/www/html;
        index index.html;
    }

    # 限制/admin目录只允许特定IP访问
    location /admin/ {
        allow 192.168.1.100;
        allow 10.0.0.0/24;
        deny all;

        root /var/www/html;
        index index.html;
    }
}

2. 使用 auth_basic 进行密码认证

location /secure/ {
    auth_basic "Restricted Area";
    auth_basic_user_file /etc/nginx/.htpasswd;

    root /var/www/html;
}

IP白名单设置

1. 全局IP白名单

http {
    # 允许的IP列表
    allow 192.168.1.100;
    allow 10.0.0.0/24;
    deny all;

    server {
        listen 80;
        server_name example.com;
        ...
    }
}

2. 特定server块的IP白名单

server {
    listen 80;
    server_name example.com;

    # IP白名单
    allow 192.168.1.100;
    allow 10.0.0.0/24;
    deny all;

    ...
}

3. 结合geo模块的动态IP控制

http {
    # 定义IP组
    geo $whitelist {
        default 0;
        192.168.1.100 1;
        10.0.0.0/24 1;
    }

    server {
        listen 80;
        server_name example.com;

        # 如果不是白名单IP则返回403
        if ($whitelist = 0) {
            return 403;
        }

        ...
    }
}

综合示例:目录+IP白名单

server {
    listen 80;
    server_name example.com;

    # 默认允许所有IP访问公共区域
    location / {
        root /var/www/html/public;
        index index.html;
    }

    # 管理后台 - 需要特定IP
    location /admin/ {
        allow 192.168.1.100;
        allow 10.0.0.0/24;
        deny all;

        root /var/www/html/admin;
        index index.html;
    }

    # API接口 - 需要认证
    location /api/ {
        auth_basic "API Access";
        auth_basic_user_file /etc/nginx/.htpasswd;

        root /var/www/html/api;
        index index.php;
    }
}

注意事项

  1. 配置修改后需要重载Nginx:nginx -s reload
  2. 规则的顺序很重要 - Nginx会按顺序匹配,第一个匹配的规则会生效
  3. 对于复杂的访问控制,可以考虑使用mapgeo模块
  4. 生产环境建议将IP白名单配置放在单独的文件中,便于管理

高级用法

使用include管理大量IP

# 在nginx.conf中
http {
    include /etc/nginx/whitelist.conf;
}

# /etc/nginx/whitelist.conf内容
allow 192.168.1.100;
allow 192.168.1.101;
# ...更多IP

结合防火墙

对于更严格的安全要求,可以在操作系统防火墙层面(如iptables/nftables)设置IP白名单,作为Nginx配置的补充。

希望这些配置示例能帮助您实现Nginx的访问控制需求。根据您的具体场景选择适合的方案。