Note: This guide needs root access. VPS and dedicated server customers have it. Shared hosting accounts do not.
What are these words?
An IP address is a number that identifies a computer on the internet. It works like a home address for a device.
Nginx (say "engine-x") is software that serves websites to visitors. You can tell it to refuse some visitors.
Before you start
A wrong setting can stop Nginx from starting and take your site offline. Back up the file you edit. Also, never block your own IP address.
Steps
- Connect to your server with SSH. SSH is a safe way to type commands on a remote computer.
- Back up your site file. Replace
example.comwith your own file name.
This command makes a safe copy.cp /etc/nginx/conf.d/example.com.conf /etc/nginx/conf.d/example.com.conf.bak - Open the file in an editor.
nano /etc/nginx/conf.d/example.com.conf - Find the
server { ... }block. - Inside it, add one line for each address you want to block.
This blocks one address. The number here is only an example.deny 203.0.113.5; - To block a whole range, use a slash.
deny 203.0.113.0/24; - If you want to allow everyone else, add this after the deny lines.
allow all; - Save the file. In nano, press Ctrl+O, Enter, then Ctrl+X.
- Test your settings.
This checks for mistakes. Do not go on if it shows an error.nginx -t - Reload Nginx.
This applies the change without stopping the site.systemctl reload nginx
Check that it works
A blocked visitor sees a 403 Forbidden message. This means "you are not allowed in."
Unblock an address
Remove the deny line, run nginx -t, then reload again.
Tip: Config file locations differ by setup. Some servers use
/etc/nginx/sites-available/ instead of conf.d.Quick recap
- Use SSH and back up your Nginx file.
- Add
deny IP;lines inside theserverblock. - Run
nginx -tto test. - Run
systemctl reload nginxto apply.