search
HomeOperation and MaintenanceNginxHow do websites set black/whitelist IP restrictions and country and city IP access restrictions through nginx?

    1. Black/white list IP restricted access configuration

    There are several ways to configure black and white lists in nginx. Here are only two commonly used methods.

    1. The first method: allow, deny

    The deny and allow instructions belong to ngx_http_access_module. nginx loads this module by default, so it can be used directly.

    This method is the simplest and most direct. Set up similar to firewall iptable, usage method:

    Add directly to the configuration file:

    #白名单设置,allow后面为可访问IP 
    location / {
         allow 123.13.123.12;
         allow 23.53.32.1/100;
         deny  all;
    }
    
    #黑名单设置,deny后面接限制的IP,为什么不加allow all? 因为这个默认是开启的 
    location / {
         deny 123.13.123.12;
    }
    
    #白名单,特定目录访问限制
    location /tree/list {
         allow 123.13.123.12;
         deny  all;
    }

    or configure the whitelist by reading the file IP

    location /{
        include /home/whitelist.conf;
        #默认位置路径为/etc/nginx/ 下,
        #如直接写include whitelist.conf,则只需要在/etc/nginx目录下创建whitelist.conf
        deny all;
    }

    Create in the /home/ directory whitelist.conf, and write the IP that needs to be added to the whitelist. After the addition is completed, view the following:

    cat /home/whitelist.conf
    
    #白名单IP
    allow 10.1.1.10;
    allow 10.1.1.11;

    The whitelist setting is completed, and the blacklist setting method is the same.

    2: The second method, ngx_http_geo_module

    By default, this module is usually added to nginx. ngx_http_geo_module: Official document, the parameters need to be set in the http module.

    This module can set IP restrictions and country and region restrictions. The location can be outside the server module.

    Syntax example:

    Add the configuration file directly

    geo $ip_list {
        default 0;
        #设置默认值为0
        192.168.1.0/24 1;
        10.1.0.0/16    1;
    }
    server {
        listen       8081;
        server_name  192.168.152.100;
        
        location / {
            root   /var/www/test;
    		index  index.html index.htm index.php;
    		if ( $ip_list = 0 ) {
    		#判断默认值,如果值为0,可访问,这时上面添加的IP为黑名单。
    		#白名单,将设置$ip_list = 1,这时上面添加的IP为白名单。
    		proxy_pass http://192.168.152.100:8081;
        }

    You can also read the file IP configuration

    geo $ip_list {
        default 0;
        #设置默认值为0
        include ip_white.conf;
    }
    server {
        listen       8081;
        server_name  192.168.152.100;
        
        location / {
            root   /var/www/test;
    		index  index.html index.htm index.php;
    		if ( $ip_list = 0 ) {
    			return 403;
    			#限制的IP返回值为403,也可以设置为503,504其他值。
    			#建议设置503,504这样返回的页面不会暴露nginx相关信息,限制的IP看到的信息只显示服务器错误,无法判断真正原因。
        }

    Create ip_list in the /etc/nginx directory .conf, after adding the IP, view the following:

    cat /etc/nginx/ip_list.conf
    
    192.168.152.1 1;
    192.168.150.0/24 1;

    When the setting is completed, the IP list file ip_list.conf will be used as a whitelist. If the requested IP is not in the list, the 403 page will be returned directly. The blacklist setting method is the same.

    3. ngx_http_geo_module load balancing (extension)

    ngx_http_geo_module, the module can also be used for load balancing, such as web clusters with servers in different regions, IP segments in a certain region, load balancing to access Servers in a certain region. A similar way is to add custom values ​​behind the IP. These values ​​are not limited to numbers, but letters can also be used, such as US, CN, etc.

    Example:

    If there are three servers: 122.11.11.11, 133.11.12.22, 144.11.11.33

    geo $country {
        default default;
        111.11.11.0/24   uk;
        #IP段定义值uk
        111.11.12.0/24   us;
        #IP段定义值us
        }
    upstream  uk.server {
        erver 122.11.11.11:9090;
        #定义值uk的IP直接访问此服务器
    } 
    
    upstream  us.server {
        server 133.11.12.22:9090;
        #定义值us的IP直接访问此服务器
    }
    
    upstream  default.server {
        server 144.11.11.33:9090;
        #默认的定义值default的IP直接访问此服务器
    }
     
    server {
        listen    9090;
        server_name 144.11.11.33;
    
        location / {
          root  /var/www/html/;
          index index.html index.htm;
         }
     }

    Then

    2. Country and region IP Restricting access

    Some third-party services such as cloudflare also provide setting options to make the setting of firewall rules more convenient. Here we talk about how to set up nginx.

    1: Install the ngx_http_geoip_module module

    ngx_http_geoip_module: Official document, the parameters need to be set in the http module.

    nginx does not build this module by default, it should be enabled using the --with-http_geoip_module configuration parameter.

    For Ubuntu systems, install nginx-extras components directly, including almost all modules.

    sudo apt install nginx-extras

    For centos system, install the module.

    yum install nginx-module-geoip

    2. Download the IP database

    This module depends on the IP database. All data is read in this database, and the ip library (dat format) needs to be downloaded.

    MaxMind provides a free IP geographical database. The bad news is that MaxMind has officially stopped supporting the dat format IP database.

    You can find dat format files in other places, or old versions. Of course, the data cannot be the latest, and there are some errors.

    Download includes country and city versions of both Ipv4 and Ipv6.

    #下载国家IP库,解压并移动到nginx配置文件目录,
    sudo wget https://dl.miyuru.lk/geoip/maxmind/country/maxmind.dat.gz
    gunzip maxmind.dat.gz
    sudo mv maxmind.dat /etc/nginx/GeoCountry.dat
    
    sudo wget https://dl.miyuru.lk/geoip/maxmind/city/maxmind.dat.gz
    gunzip maxmind.dat.gz
    sudo mv maxmind.dat /etc/nginx/GeoCity.dat

    3. Configure nginx

    Example:

    geoip_country /etc/nginx/GeoCountry.dat;
    geoip_city /etc/nginx/GeoCity.dat;
    
    server {
        listen  80;
        server_name 144.11.11.33;
    
        location / {
          root  /var/www/html/;
          index index.html index.htm;
          if ($geoip_country_code = CN) {
      			return 403;
     		#中国地区,拒绝访问。返回403页面
    		}
      	}
     }

    Here, the regional and country basic settings are completed.

    Geoip other parameters:

    Country-related parameters:
    $geoip_country_code #Two-character English country code. For example: CN, US
    $geoip_country_code3 #A three-character English country code. For example: CHN, USA
    $geoip_country_name #The full English name of the country. For example: China, United States
    City related parameters:
    $geoip_city_country_code # is also a two-character English country code.
    $geoip_city_country_code3 #Same as above
    $geoip_city_country_name #Same as above.
    $geoip_region #This has been tested to be a two-digit number, such as 02 for Hangzhou and 23 for Shanghai. However, no relevant information was found. I hope friends who know more can leave a message.
    $geoip_city #The English name of the city. For example: Hangzhou
    $geoip_postal_code #The postal code of the city. After testing, this field is empty in China
    $geoip_city_continent_code #I don’t know what it is used for, but it seems to be AS
    $geoip_latitude #Latitude
    $geoip_longitude #Longitude

    The above is the detailed content of How do websites set black/whitelist IP restrictions and country and city IP access restrictions through nginx?. 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 Unit: Supporting Different Programming LanguagesNGINX Unit: Supporting Different Programming LanguagesApr 16, 2025 am 12:15 AM

    NGINXUnit supports multiple programming languages ​​and is implemented through modular design. 1. Loading language module: Load the corresponding module according to the configuration file. 2. Application startup: Execute application code when the calling language runs. 3. Request processing: forward the request to the application instance. 4. Response return: Return the processed response to the client.

    Choosing Between NGINX and Apache: The Right Fit for Your NeedsChoosing Between NGINX and Apache: The Right Fit for Your NeedsApr 15, 2025 am 12:04 AM

    NGINX and Apache have their own advantages and disadvantages and are suitable for different scenarios. 1.NGINX is suitable for high concurrency and low resource consumption scenarios. 2. Apache is suitable for scenarios where complex configurations and rich modules are required. By comparing their core features, performance differences, and best practices, you can help you choose the server software that best suits your needs.

    How to start nginxHow to start nginxApr 14, 2025 pm 01:06 PM

    Question: How to start Nginx? Answer: Install Nginx Startup Nginx Verification Nginx Is Nginx Started Explore other startup options Automatically start Nginx

    How to check whether nginx is startedHow to check whether nginx is startedApr 14, 2025 pm 01:03 PM

    How to confirm whether Nginx is started: 1. Use the command line: systemctl status nginx (Linux/Unix), netstat -ano | findstr 80 (Windows); 2. Check whether port 80 is open; 3. Check the Nginx startup message in the system log; 4. Use third-party tools, such as Nagios, Zabbix, and Icinga.

    How to close nginxHow to close nginxApr 14, 2025 pm 01:00 PM

    To shut down the Nginx service, follow these steps: Determine the installation type: Red Hat/CentOS (systemctl status nginx) or Debian/Ubuntu (service nginx status) Stop the service: Red Hat/CentOS (systemctl stop nginx) or Debian/Ubuntu (service nginx stop) Disable automatic startup (optional): Red Hat/CentOS (systemctl disabled nginx) or Debian/Ubuntu (syst

    How to configure nginx in WindowsHow to configure nginx in WindowsApr 14, 2025 pm 12:57 PM

    How to configure Nginx in Windows? Install Nginx and create a virtual host configuration. Modify the main configuration file and include the virtual host configuration. Start or reload Nginx. Test the configuration and view the website. Selectively enable SSL and configure SSL certificates. Selectively set the firewall to allow port 80 and 443 traffic.

    How to solve nginx403 errorHow to solve nginx403 errorApr 14, 2025 pm 12:54 PM

    The server does not have permission to access the requested resource, resulting in a nginx 403 error. Solutions include: Check file permissions. Check the .htaccess configuration. Check nginx configuration. Configure SELinux permissions. Check the firewall rules. Troubleshoot other causes such as browser problems, server failures, or other possible errors.

    How to start nginx in LinuxHow to start nginx in LinuxApr 14, 2025 pm 12:51 PM

    Steps to start Nginx in Linux: Check whether Nginx is installed. Use systemctl start nginx to start the Nginx service. Use systemctl enable nginx to enable automatic startup of Nginx at system startup. Use systemctl status nginx to verify that the startup is successful. Visit http://localhost in a web browser to view the default welcome page.

    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

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Chat Commands and How to Use Them
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools

    EditPlus Chinese cracked version

    EditPlus Chinese cracked version

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

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.