How to protect a directory with user and password on Nginx


Username and password protection

There are a few ways to protect a directory with username and password, but today I will show you the way to do it using http authentication on Nginx web server. We will use the same mechanism that uses Apache for the user and pass authentication, and that is using a .htpasswd file. Let’s start.

Create a file called .htpasswd

htpasswd -bc /var/www/.htpasswd steve password

If you need to add an extra user:

htpasswd -b /var/www/.htpasswd jack password

On this two examples steve and jack are usernames, and ‘password’ is the password set, of course, change this to fit your needs.

Important: note that the .htpasswd file should be placed above your pubic_html root directory or inside another non-public accessible directory. You can place it for example at /var/www/.htpasswd or /home/jack/.htpasswd, it’s up to you.

Edit Nginx configuration to add the password protected directory settings

Place this lines inside the server-block {}:

 location ^~ /secret_directory/ { auth_basic "Restricted"; auth_basic_user_file /var/www/.htpasswd;          location ~ .php$  {             root           /var/www/;             try_files $ uri =404;        	    fastcgi_pass   unix:/tmp/php5-fpm.sock;             fastcgi_index  index.php;             fastcgi_param  SCRIPT_FILENAME  $ document_root$ fastcgi_script_name;             include        fastcgi_params;             fastcgi_buffer_size 128k;             fastcgi_buffers 256 4k;             fastcgi_busy_buffers_size 256k;             fastcgi_temp_file_write_size 256k;         } }

Replace “secret_directory” with the real name of the directory you want to protect.
I’ve also pasted here the configuration I use on php-fpm, which is based on sockets, it may differ from yours.

Reload Nginx to apply the changes:

 /etc/init.d/nginx reload

Test the password protected directory

Go to and you should see the protection working.