Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

Block an IP Address with Nginx

This guide shows you how to stop a bad visitor from reaching your website by blocking their IP address in Nginx.

How-To Guides2 min read10 steps

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

  1. Connect to your server with SSH. SSH is a safe way to type commands on a remote computer.
  2. Back up your site file. Replace example.com with your own file name.
    cp /etc/nginx/conf.d/example.com.conf /etc/nginx/conf.d/example.com.conf.bak
    This command makes a safe copy.
  3. Open the file in an editor.
    nano /etc/nginx/conf.d/example.com.conf
  4. Find the server { ... } block.
  5. Inside it, add one line for each address you want to block.
    deny 203.0.113.5;
    This blocks one address. The number here is only an example.
  6. To block a whole range, use a slash.
    deny 203.0.113.0/24;
  7. If you want to allow everyone else, add this after the deny lines.
    allow all;
  8. Save the file. In nano, press Ctrl+O, Enter, then Ctrl+X.
  9. Test your settings.
    nginx -t
    This checks for mistakes. Do not go on if it shows an error.
  10. Reload Nginx.
    systemctl reload nginx
    This applies the change without stopping the site.

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 the server block.
  • Run nginx -t to test.
  • Run systemctl reload nginx to apply.