Table of Contents
1. Black/white list IP restricted access configuration
1. The first method: allow, deny
2: The second method, ngx_http_geo_module
3. ngx_http_geo_module load balancing (extension)
2. Country and region IP Restricting access
1: Install the ngx_http_geoip_module module
2. Download the IP database
3. Configure nginx
Home Operation and Maintenance Nginx How do websites set black/whitelist IP restrictions and country and city IP access restrictions through nginx?

How do websites set black/whitelist IP restrictions and country and city IP access restrictions through nginx?

Jun 01, 2023 pm 05:27 PM
nginx ip

    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;
    }
    Copy after login

    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;
    }
    Copy after login

    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;
    Copy after login

    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;
        }
    Copy after login

    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看到的信息只显示服务器错误,无法判断真正原因。
        }
    Copy after login

    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;
    Copy after login

    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;
         }
     }
    Copy after login

    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
    Copy after login

    For centos system, install the module.

    yum install nginx-module-geoip
    Copy after login

    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
    Copy after login

    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页面
    		}
      	}
     }
    Copy after login

    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 of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    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

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    How to check the name of the docker container How to check the name of the docker container Apr 15, 2025 pm 12:21 PM

    You can query the Docker container name by following the steps: List all containers (docker ps). Filter the container list (using the grep command). Gets the container name (located in the "NAMES" column).

    How to configure nginx in Windows How to configure nginx in Windows Apr 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 check whether nginx is started How to check whether nginx is started Apr 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 start containers by docker How to start containers by docker Apr 15, 2025 pm 12:27 PM

    Docker container startup steps: Pull the container image: Run "docker pull [mirror name]". Create a container: Use "docker create [options] [mirror name] [commands and parameters]". Start the container: Execute "docker start [Container name or ID]". Check container status: Verify that the container is running with "docker ps".

    How to configure cloud server domain name in nginx How to configure cloud server domain name in nginx Apr 14, 2025 pm 12:18 PM

    How to configure an Nginx domain name on a cloud server: Create an A record pointing to the public IP address of the cloud server. Add virtual host blocks in the Nginx configuration file, specifying the listening port, domain name, and website root directory. Restart Nginx to apply the changes. Access the domain name test configuration. Other notes: Install the SSL certificate to enable HTTPS, ensure that the firewall allows port 80 traffic, and wait for DNS resolution to take effect.

    How to check nginx version How to check nginx version Apr 14, 2025 am 11:57 AM

    The methods that can query the Nginx version are: use the nginx -v command; view the version directive in the nginx.conf file; open the Nginx error page and view the page title.

    How to create containers for docker How to create containers for docker Apr 15, 2025 pm 12:18 PM

    Create a container in Docker: 1. Pull the image: docker pull [mirror name] 2. Create a container: docker run [Options] [mirror name] [Command] 3. Start the container: docker start [Container name]

    How to start nginx server How to start nginx server Apr 14, 2025 pm 12:27 PM

    Starting an Nginx server requires different steps according to different operating systems: Linux/Unix system: Install the Nginx package (for example, using apt-get or yum). Use systemctl to start an Nginx service (for example, sudo systemctl start nginx). Windows system: Download and install Windows binary files. Start Nginx using the nginx.exe executable (for example, nginx.exe -c conf\nginx.conf). No matter which operating system you use, you can access the server IP

    See all articles