search
HomeOperation and MaintenanceNginxHow to configure blacklist or whitelist function for Nginx server

1. Method of defining blacklist or whitelist:
1. Configuration format
Configure keyword blacklist or whitelist file storage space
white_black_list_conf conf/white.list zone =white:2m;
| | | |
| | | -------------------------------- ------The storage space size here is 2m. The space size determines the capacity of the black and white list
| | -------------------------- -------------------------------------------------- ------------------Storage space name
| ---------------------------- -----------------------------------------------Blacklist or whitelist configuration file path
- --------------------------------------------------Configuration command
2. Configure the keyword white_black_list_conf.
3. Can only be used in http{}
4. White_black_list_conf can be configured with multiple zones=value as long as the values ​​are different
5. Configuration example:

http{
    ......
    white_black_list_conf conf/white.list zone=white:4m;
    white_black_list_conf conf/black.list zone=black:4m;
    ......
    server{
    .......
    }
    .......
}

2. Scope of black and white lists
1. Configuration format
Configuration keywords on/off
The configuration keywords are: white_list and black_list are used to represent white list and black list respectively.
2. Can be used under http{}, server{}, location{}, the function is turned off by default
3. Configuration example:

http{
    ......
    white_black_list_conf conf/white.list zone=white1:4m;
    white_black_list_conf conf/black.list zone=black1:4m;
    white_list white1 on; #白名单 white1 在整个http{} 中都开启
    black_list black1 on; #黑名单 black1 在整个http{} 中都开启
    server{
        .......
    }
    .......
}
http{
    ......
    white_black_list_conf conf/white.list zone=white2:4m;
    white_black_list_conf conf/black.list zone=black2:4m;
    server{
        .......
        white_list white2 on; #白名单 white1 在整个server{} 中都开启
        black_list black2 on; #黑名单 black1 在整个server{} 中都开启
        .......
    }
    .......
}
http{
    ......
    white_black_list_conf conf/white.list zone=white3:4m;
    white_black_list_conf conf/black.list zone=black3:4m;
    white_black_list_conf conf/black.list zone=black2:4m;
    white_black_list_conf conf/white.list zone=white2:4m;
    server{
        .......
        location /do {
            ........
            white_list white3 on; #白名单 white3 在location /do{} 中开启
            black_list black3 on; #黑名单 black3 在location /do{} 中开启
            ........
        }
        location /do1{
            white_list white2 on; #白名单 white2 在整个server{} 中都开启
            black_list black2 on; #黑名单 black2 在整个server{} 中都开启
        }
        .......
    }
    .......
}

4.http configuration interface description:
(1) Configuration configuration interface

http{
    .......
    server{
        ......
        location /sec_config{
            sec_config on;
        }
        ......
    }
    .......
}

(2) Configuration method:
a. http://xxx/sec_config Check the black and white list definition
The return results are as follows

{
    "version":    "nginx/1.3.0",
    "code":    "0",
    "item":    {
        "conf_type":    "white_black_list_conf",
        "zone_name":    "white",
        "list_path":    "/home/john/nginx/conf/white.list"
    },
    "item":    {
        "conf_type":    "white_black_list_conf",
        "zone_name":    "black",
        "list_path":    "/home/john/nginx/conf/black.list"
    },
    "item":    {
        "conf_type":    "white_black_list_conf",
        "zone_name":    "ex",
        "list_path":    "/home/john/nginx/conf/status_ex"
    }
}

b. http://xxx/sec_config?zone_name=white View the specific content in the list_path where zone_name is white
c. http://xxx/sec_config?zone_name=white&add_item=192.168. 141.23 Add 192.168.141.23
d to zone_name is white. http://xxx/sec_config?zone_name=white&delete_item=192.168.141.23 Delete 192.168.141.23
to zone_name is white. View configuration method 2:
http://xxx/sec_config?for_each
3. The content of the black and white list file
conf/black.list The content of the file is as follows

2.2.2.2
192.168.141.1
3.3.3.3
4.4.4.5
2.3.4.4

4. Dynamic blacklist
To use this function, you must patch ngx_http_limit_req_module.c
In ngx_http_limit_req_module.c
Add #include
and modify the code to find:

  "
  if (rc == ngx_busy) {
    ngx_log_error(lrcf->limit_log_level, r->connection->log, 0,
           "limiting requests, excess: %ui.%03ui by zone \"%v\"",
           excess / 1000, excess % 1000,
           &limit->shm_zone->shm.name);
    "

Add below it:

  ngx_black_add_item_interface(r, 1);

Equipped keywords:
dyn_black
Format:
dyn_black $zone_name time;
For example:
Dyn_black Black 60; // Forbidden access for 60 seconds, and automatically dismiss
Note after 60 seconds:
must be configured with BLACK_LIST
Configuration Example:

## PS PS : ngx_lua_waf firewall based on lua-nginx-module

Project address: https://github.com/loveshell/ngx_lua_waf?utm_source=tuicool&utm_medium=referral

Recommended installation:

Recommended to use lujit2.1 for lua support

If ngx_lua is version 0.9.2 or above, it is recommended to change the regular filter function to ngx.re.find, which will increase the matching efficiency by about three times.

Instructions for use:

nginx installation path is assumed to be:/usr/local/nginx/conf/

Download ngx_lua_waf to the conf directory, unzip it and name it waf

Add the http section of nginx.conf

http{
            ....
            white_black_list_conf conf/black.list zone=black:4m;
            limit_req_zone $binary_remote_addr zone=one:8m rate=4r/s;
            ...
            server {
                location / {
         black_list black on;
         limit_req zone=one burst=6;
         dyn_black black 60; //禁止访问60秒,60秒后自动解除
         ...
         }
         location /xxx {
         sec_config on;
         }
         ...
            }
            ...
        }

Configure the waf rule directory in config.lua (usually in the waf/conf/ directory)

  lua_package_path "/usr/local/nginx/conf/waf/?.lua";
  lua_shared_dict limit 10m;
  init_by_lua_file /usr/local/nginx/conf/waf/init.lua; 
  access_by_lua_file /usr/local/nginx/conf/waf/waf.lua;

The absolute path is subject to change , you need to modify it accordingly

and then restart nginx

Detailed description of the configuration file:

  rulepath = "/usr/local/nginx/conf/waf/wafconf/"
  --规则存放目录
  attacklog = "off"
  --是否开启攻击信息记录,需要配置logdir
  logdir = "/usr/local/nginx/logs/hack/"
  --log存储目录,该目录需要用户自己新建,切需要nginx用户的可写权限
  urldeny="on"
  --是否拦截url访问
  redirect="on"
  --是否拦截后重定向
  cookiematch = "on"
  --是否拦截cookie攻击
  postmatch = "on"
  --是否拦截post攻击
  whitemodule = "on"
  --是否开启url白名单
  ipwhitelist={"127.0.0.1"}
  --ip白名单,多个ip用逗号分隔
  ipblocklist={"1.0.0.1"}
  --ip黑名单,多个ip用逗号分隔
  ccdeny="on"
  --是否开启拦截cc攻击(需要nginx.conf的http段增加lua_shared_dict limit 10m;)
  ccrate = "100/60"
  --设置cc攻击频率,单位为秒.
  --默认1分钟同一个ip只能请求同一个地址100次
  html=[[please go away~~]]
  --警告内容,可在中括号内自定义
  备注:不要乱动双引号,区分大小写

检查规则是否生效

部署完毕可以尝试如下命令:

  curl http://xxxx/test.php?id=../etc/passwd

    返回"please go away~~"字样,说明规则生效。
注意:默认,本机在白名单不过滤,可自行调整config.lua配置

How to configure blacklist or whitelist function for Nginx server

How to configure blacklist or whitelist function for Nginx server

规则更新:

考虑到正则的缓存问题,动态规则会影响性能,所以暂没用共享内存字典和redis之类东西做动态管理。

规则更新可以把规则文件放置到其他服务器,通过crontab任务定时下载来更新规则,nginx reload即可生效。以保障ngx lua waf的高性能。

只记录过滤日志,不开启过滤,在代码里在check前面加上--注释即可,如果需要过滤,反之

一些说明:

过滤规则在wafconf下,可根据需求自行调整,每条规则需换行,或者用|分割

  •   global是全局过滤文件,里面的规则对post和get都过滤 

  •   get是只在get请求过滤的规则  

  •   post是只在post请求过滤的规则  

  •   whitelist是白名单,里面的url匹配到不做过滤   

  •   user-agent是对user-agent的过滤规则

默认开启了get和post过滤,需要开启cookie过滤的,编辑waf.lua取消部分--注释即可

日志文件名称格式如下:虚拟主机名_sec.log

The above is the detailed content of How to configure blacklist or whitelist function for Nginx server. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
NGINX vs. Apache: Examining the Pros and ConsNGINX vs. Apache: Examining the Pros and ConsApr 27, 2025 am 12:05 AM

NGINX is suitable for handling high concurrent and static content, while Apache is suitable for complex configurations and dynamic content. 1. NGINX efficiently handles concurrent connections, suitable for high-traffic scenarios, but requires additional configuration when processing dynamic content. 2. Apache provides rich modules and flexible configurations, which are suitable for complex needs, but have poor high concurrency performance.

NGINX and Apache: Understanding the Key DifferencesNGINX and Apache: Understanding the Key DifferencesApr 26, 2025 am 12:01 AM

NGINX and Apache each have their own advantages and disadvantages, and the choice should be based on specific needs. 1.NGINX is suitable for high concurrency scenarios because of its asynchronous non-blocking architecture. 2. Apache is suitable for low-concurrency scenarios that require complex configurations, because of its modular design.

NGINX Unit: Key Features and CapabilitiesNGINX Unit: Key Features and CapabilitiesApr 25, 2025 am 12:17 AM

NGINXUnit is an open source application server that supports multiple programming languages ​​and provides functions such as dynamic configuration, zero downtime updates and built-in load balancing. 1. Dynamic configuration: You can modify the configuration without restarting. 2. Multilingual support: compatible with Python, Go, Java, PHP, etc. 3. Zero downtime update: Supports application updates that do not interrupt services. 4. Built-in load balancing: Requests can be distributed to multiple application instances.

NGINX Unit vs. Other Application ServersNGINX Unit vs. Other Application ServersApr 24, 2025 am 12:14 AM

NGINXUnit is better than ApacheTomcat, Gunicorn and Node.js built-in HTTP servers, suitable for multilingual projects and dynamic configuration requirements. 1) Supports multiple programming languages, 2) Provides dynamic configuration reloading, 3) Built-in load balancing function, suitable for projects that require high scalability and reliability.

NGINX Unit: The Architecture and How It WorksNGINX Unit: The Architecture and How It WorksApr 23, 2025 am 12:18 AM

NGINXUnit improves application performance and manageability with its modular architecture and dynamic reconfiguration capabilities. 1) Modular design includes master processes, routers and application processes, supporting efficient management and expansion. 2) Dynamic reconfiguration allows seamless update of configuration at runtime, suitable for CI/CD environments. 3) Multilingual support is implemented through dynamic loading of language runtime, improving development flexibility. 4) High performance is achieved through event-driven models and asynchronous I/O, and remains efficient even under high concurrency. 5) Security is improved by isolating application processes and reducing the mutual influence between applications.

Using NGINX Unit: Deploying and Managing ApplicationsUsing NGINX Unit: Deploying and Managing ApplicationsApr 22, 2025 am 12:06 AM

NGINXUnit can be used to deploy and manage applications in multiple languages. 1) Install NGINXUnit. 2) Configure it to run different types of applications such as Python and PHP. 3) Use its dynamic configuration function for application management. Through these steps, you can efficiently deploy and manage applications and improve project efficiency.

NGINX vs. Apache: A Comparative Analysis of Web ServersNGINX vs. Apache: A Comparative Analysis of Web ServersApr 21, 2025 am 12:08 AM

NGINX is more suitable for handling high concurrent connections, while Apache is more suitable for scenarios where complex configurations and module extensions are required. 1.NGINX is known for its high performance and low resource consumption, and is suitable for high concurrency. 2.Apache is known for its stability and rich module extensions, which are suitable for complex configuration needs.

NGINX Unit's Advantages: Flexibility and PerformanceNGINX Unit's Advantages: Flexibility and PerformanceApr 20, 2025 am 12:07 AM

NGINXUnit improves application flexibility and performance with its dynamic configuration and high-performance architecture. 1. Dynamic configuration allows the application configuration to be adjusted without restarting the server. 2. High performance is reflected in event-driven and non-blocking architectures and multi-process models, and can efficiently handle concurrent connections and utilize multi-core CPUs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function