Website access restriction using nginx

You can restrict access to certain part of your website using nginx’s inbuilt authentication and authorization mechanism based either on your client’s I.P, by prompting for a login prompt or both.

A sample I.P. based authorization configuration would be like:

location /private/ {
allow 192.168.1.1/24;
allow 172.16.0.1/16;
allow 127.0.0.1;
deny all;
}

Note: In above example /private/ is the website address you want to restrict access to and 192.*, 172.*, 127.* represents I.P addresses you want to allow access to.

allow and deny are the two keyword that can be used to grant or restrict access to the desired part of your website.

ADVERTISEMENT

To enable authentication, you will need to use the auth_basic directive. The auth_basic_user_file directive is used to define a list of allowed users with their respective passwords. For the purpose of access restriction, nginx uses HTTP basic authentication.

server {
    ...
    auth_basic "Restricted access";
    auth_basic_user_file common/authenticator;
}

You can still allow certain parts of the website to be publicly accessible. In such a case you will need to pass off parameters to auth_basic under a location block with the publicly accessible url.

server {
    ...
    auth_basic "Restricted access";
    auth_basic_user_file common/authenticator;

ADVERTISEMENT
location /private/public/ { auth_basic off; } }

If you have both I.P. based authorization and HTTP based authentication mechanism enabled, by default a user will have to qualify both restriction to be able to have access to the desired page. You can change this behavior by using the directive satisfy. It takes two values either all or any, by default, it is implicitly set to all, that can be overridden by using any to allow a user based on either their I.P or their username and password.

location /private/ {
    satisfy any;

    allow 192.168.1.1/24;
    allow 172.16.0.1/16;
    allow 127.0.0.1;
    deny all;

    auth_basic "Restricted access";
    auth_basic_user_file common/authenticator;

    location /private/public/ {
        auth_basic off;
}