Contents...
If you want to block or deny access of your website from particular IP address or whole Network address in Nginx then this article will help you to do so.
Nginx by default comes with simple module called ngx_http_access_module to allow or deny access to IP address. Follow the below syntax:
deny IP; deny subnet; allow IP; allow subnet; # block all ips deny all; # allow all ips allow all;
Note :- Above rules are checked in the order of their record to the first match.
Configure Nginx To Block IPs
To block the IPs, edit the nginx.conf file and like below:
# cd /etc/nginx # vi nginx.conf
Now add the following line in the http section.
## Block spammers and other unwanted visitors ##
include blacklist_IPs.conf;
Save and close the file. Now create the file called “blacklist_IPs.conf” in /etc/nginx/ directory.
Add the below entries in file like below:
# vim blacklist_IPs.conf deny 192.168.0.5; deny 192.168.0.0/24; deny 91.212.1.0/24;
Save and close the file. Now test the configuration file for syntax check.
# nginx -t
Sample outputs:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
Reload the Nginx typing below command.
# service nginx relaod
Deny All and Allow Only Lan IPs
Edit Nginx configuration file like below:
location / { # block one IP deny 192.168.0.5; # allow anyone in 192.168.0.0/24 allow 192.168.0.0/24; # drop rest of the world deny all; }
Custom HTTP 403 Forbidden Error Page
You can also create a custom page for 403 error page. You have to create a file called ” 403.html” in your default web root directory.
# cd /var/www/html/ # vim 403.html <html> <head><title>Error 403 - You are not authorized to access this page.</title></head> <body> You are not authorized to access this page. If you this an error, please contact webmaster with your IP at [email protected] </body> </html>
Save and close the file.
Edit your nginx.conf file like below:
# vim nginx.conf # redirect server error pages to the static page error_page 403 /403.html; location = /403.html { root /var/www/html; }
Save and close the file and reload the Nginx.
# service nginx reload
Thanks:)
If you find this tutorial helpful please share with your friends to keep it alive. For more helpful topic browse my website www.looklinux.com. To become an author at LookLinux Submit Article. Stay connected to Facebook.
Leave a Comment