Protect a directory 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.

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

For example, 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;

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