Password Protecting Folders in Nginx

Often you may want to hide a few folders which you want to only have access to, maybe a bunch of hidden documents? But you don’t want to go through the hassle of coding a full fledged authentication system.

Here’a the quick way to get it done with Nginx’s inbuilt features:

Remember to replace:

mkdir -p /etc/nginx/  
cd /etc/nginx/  
htpasswd -b -c htpass User Password  

Now add this within your nginx server block config: /etc/nginx/sites-enabled/

location ^~ /hidden {  
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/;

If you’re hiding a PHP script such as adminer then you’ll need to add your fastcgi_params too

location ^~ /hidden {  
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/;
    try_files $uri = 404;
    fastcgi_split_path_info ^(.+.php)(.*)$;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
    fastcgi_intercept_errors on;
    fastcgi_ignore_client_abort off;
    fastcgi_connect_timeout 60;
    fastcgi_send_timeout 180;
    fastcgi_read_timeout 180;
    fastcgi_buffer_size 128k;
    fastcgi_buffers 4 256k;
    fastcgi_busy_buffers_size 256k;
    fastcgi_temp_file_write_size 256k;

Of course taking this route for password authentication I’m assuming it’s only for simple purposes, heavy tweaks aren’t necessary so you won’t really need anything below “include fastcgi_param”, as it’s just a dump from my php configuration block. But having it there won’t hurt.

And that’s all it. Restart your nginx server and check it out.

comments powered by Disqus