Protect your Magento store with a password in Nginx

in Nginx configuration Tags: Nginx

Hypernode makes use of Nginx. Nginx does not use .htaccess files like Apache does. This means that configuration now has to be done in a different format, explained in the Nginx documentation. To protect a directory with a password in Nginx, you can use the same htpasswd file that is used with Apache. To restrict access to a location, you can use the auth basic directive.

Restricting access to a directory

To restrict access to the preview-directory using users and passwords specified in the file /data/web/htpasswd, create a file called server.basicauth in /data/web/nginx containing:

location ^~ /preview/ {
  auth_basic "Restricted area";
  auth_basic_user_file /data/web/nginx/htpasswd;
  location ~ \.php$ {
    echo_exec @phpfpm;
  }
}

NOTE: Make sure to include a PHP handler to the end of a location-block, or PHP scripts inside it will not be executed!

How to create or update a htpasswd file? This command will ask you for a password and save it to the password database:

htpasswd -c /data/web/nginx/htpasswd exampleuser

Restricting access to a specific domain

Create a file called server.basicauth in /data/web/nginx with the following snippet:

if ($http_host = "domainwithbasicauth.com") {
set $auth_basic Restricted;
}

if ($http_host != "domainwithbasicauth.com") {
set $auth_basic off;
}

auth_basic $auth_basic;
auth_basic_user_file /data/web/htpasswd;

This will only restrict access to domainwithbasicauth.com with basic authentication and make all other domains on your Hypernode accessible without any authentication.

Creating a user and a password can be done with the following command:

htpasswd -c /data/web/nginx/htpasswd exampleuser

2