Restrict Access by IP Address Using Nginx

- 2 mins

Basic password authentication is not always enough to keep sensitive information secure from prying eyes. Areas such as control panels, PhpMyAdmin and other admin type interfaces should an extra layer of security in a production environment.

Why?

Attackers can exploit weak passwords or software vulnerabilities in such areas listed above to gain unauthorised access to cause havoc or steal data.

Enter IP based restriction

For example, if you have a Magento site and its admin area is at /admin/ (This should always be changed anyway but let’s roll with it for this example.), you should limit the access to it only to your IP or to the IPs of all the administrators. For this purpose, open the corresponding server block — the default server block for Nginx is /etc/nginx/conf.d/magento-store.com.conf:

sudo vim /etc/nginx/conf.d/magento-store.com.conf

Inside the server configuration part in /etc/nginx/conf.d/magento-store.com.conf add:

server {
...
    location /admin/ {
        allow 10.0.0.1;
        allow 10.0.0.2;
        deny  all;
    }
...
}

In the above please make sure to replace 10.0.0.1, 10.0.0.2 with your IPs. Similarly, you can allow access for other IPs or even networks by changing the network mask (/24).

# This will allow access for 10.0.0.1 to 10.0.0.254;
allow 10.0.0.0/24;

Always test your configuration

ALWAYS check your configuration before reloading nginx. ALWAYS!

sudo service nginx configtest
# or
sudo /usr/sbin/nginx -t

For such settings to take effect you will have to reload Nginx again with the command:

sudo service nginx reload
# or
sudo /usr/sbin/nginx -s reload

Now if you try to access the /admin/ part of your site with a browser outside of the allowed IP address ranges, you will get an error. This error will be 403 Forbidden (unless you have changed this error to 404 Not found). At the same time you will see the error code in the error log with the command:

sudo tail /var/log/nginx/error.log

The access forbidden error will show like this:

Output of sudo tail -f /var/log/nginx/error.log:

...
2016/03/15 04:16:12 [error] 4767#0: *13 access forbidden by rule, client: X.X.X.X, server: localhost, request: "GET /admin/ HTTP/1.1", host: "Y.Y.Y.Y"
...
Sergei Filippov

Sergei Filippov

Web, development, family & life.

rss facebook twitter github youtube mail instagram linkedin google