Restricting access to the site via Nginx

Restricting access to the site via Nginx

When managing a web server, it’s important to control who has access to different parts of your site. Nginx provides flexible tools for restricting access by IP, setting up authentication, and protecting sensitive files. In this article, we’ll go over the main ways to implement these restrictions.


Restricting Access to Files

To block access to files that might attract unwanted attention:

        location ~ /.svn/ {
           deny all;
        }

IP-Based Access Control

You can allow or deny access to resources from specific IP addresses using the allow and deny directives:

  location /server-status {
      allow 111.111.111.111;
      allow 11.11.11.11;
      deny all;
  }

Password Protection

For more flexible protection, you can use auth\basic and auth\basic_user\file. Users will need to enter a username and password:

  location /admin/ {
      auth_basic "Enter password to access";
      auth_basic_user_file /etc/nginx/basic.auth;
  }

Combined Protection

You can combine IP filtering and basic authentication:

  location /admin/ {
      satisfy any;
      allow 111.111.111.111;
      allow 11.11.11.11;
      deny  all;
 
      auth_basic "Enter password to access";
      auth_basic_user_file /etc/nginx/basic.auth;
  }

Protecting Against Requests to Nonexistent Files

        location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
           try_files $uri =404;
        }

Reloading Nginx

After making changes, reload Nginx using one of the following commands:

systemctl reload nginx
service nginx reload

IP-Based Redirects

Depending on the visitor’s IP address, Nginx can perform a redirect:

location / {
    
    if ($remote_addr != 111.111.111.111) {
        return 301 https://$host$request_uri;
    }
    
}

Note

In this example, all visitors will be redirected to https://$host$request_uri except requests coming from the IP address 111.111.111.111.


Protecting Against Brute-Force Password Attempts Using iptables

You can temporarily block IPs if the number of requests exceeds a set threshold:

iptables -A INPUT -p tcp --syn --dport 80 -i eth0 -m state --state NEW \
            -m recent --name bhttp --set
iptables -A INPUT -p tcp --syn --dport 80 -i eth0 -m state --state NEW \
            -m recent --name bhttp --update --seconds 120 \
            --hitcount 360 -j DROP
iptables -A INPUT -p tcp --syn --dport 80 -i eth0 -j ACCEPT

Note

On VPS and dedicated servers, you have full control over NGINX configuration. This allows you to finely tune file access, implement IP filters, enable password protection, and block brute-force attempts using iptables.

Need help?Our engineers will help you free of charge with any question in minutesContact us