Nginx IP based access control

First, create a new HTML file in the / root/access directory as the access page, named admin.html

[root@localhost code]# vim /root/access/admin.html
<html>
<head>
	<meta charset="utf-8">
	<title>vincen</title>
</head>
<body style="backgroup-color:yellow;">
<h1>Local access allowed</h1>
<h1>hello</h1>
</body>
</html>

1. Modify the configuration file of Nginx

[root@localhost ~]# vim /etc/nginx/conf.d/default.conf

Modify the path of root in the original location content

root   /root/access;  #Path to page access

Add another location after the location in the configuration file, then save and exit

location ~ ^/admin.html {
        root /root/access;     #Path to page access
        index index.html index.htm;   #Accessing html files or HTMs
        deny 61.141.96.68;           #Access denied with IP 61.141.96.68
        allow all;                   #Allow all IP access (except 61.141.96.68)
    }

2. Check whether the syntax of the configuration file is correct

[root@localhost ~]# nginx -tc /etc/nginx/nginx.conf 
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
#The above two prompts show that the syntax is correct

3. Reload Nginx service

[root@localhost ~]# nginx -s reload -c /etc/nginx/nginx.conf

4. Access the virtual machine (IP) on the local browser, that is, access Nginx. Because the profile settings deny native IP access, other IPS can access it.

(403 forbidden means no access). (if there is VPN or proxy, other IP can be used for testing)

5. Go back to modify the configuration file of Nginx at this time

[root@localhost ~]# vim /etc/nginx/conf.d/default.conf

Modify the content of the location just added to allow local IP access, other IP cannot access

location ~^/admin.html{
        root /root/access;
        index index.html index.htm;
        deny all;                #Deny all IP access
        allow 61.141.96.68;      #Allow IP 61.141.96.68 access
    }

6. Check the syntax of Nginx, and carry out overload service after confirming there is no error

[root@localhost ~]# nginx -tc /etc/nginx/nginx.conf 
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@localhost ~]# nginx -s reload -c /etc/nginx/nginx.conf

7. When accessing the virtual machine in the browser, the machine is successfully accessed. (if there is VPN or proxy, other IP can be used for testing)

Tags: Operation & Maintenance Nginx vim VPN

Posted on Sat, 14 Dec 2019 11:44:47 -0500 by mark_php