Nginx-logo The first thing you will need to do is create a file called .htpasswd (it doesn’t have to be named that way). The following command creates a new .htpasswd file and stores a record in it for user tom.

htpasswd -bc /var/www/ tom password

To create another user:

htpasswd -b /var/www/ john password

If you get a “command not found” error you probably don’t have apache2-utils installed.
.htpasswd should be placed above your www root directory or in another non-web accessible directory.

Next edit your site’s configuration file by adding the following lines of code inside the server-block:

location ^~ /secretdirectory/ {
    auth_basic            "Restricted";
    auth_basic_user_file  /var/www/;

    location ~ \.php {
        fastcgi_index index.php;
        fastcgi_split_path_info ^(.+\.php)(.*)$;
        include /etc/nginx/fastcgi_params;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;

Restart nginx for the configuration changes to take effect

/etc/init.d/nginx restart

Finally test if everything is working correctly. Go to and you should be prompted for your username and password.

PS. If you liked this post please share it with your friends on the social networks using the buttons on the left or simply leave a reply below. Thanks.