Nginx: Protecting a folder using htaccess

First we need to install the htpasswd application, it is located in the apache2-utils package. This package has no dependencies on apache, so it is safe to install it – it will not download the full apache for you 🙂

To install it on ubuntu type:

sudo apt-get install apache2-utils

Once installed we can use it to create an htaccess file.

htpasswd -c -b /path/to/htpasswd NewUser NewPassword

Now we need to add one block to the nginx config. Bellow is the config for this site, the part in bold is what needs to be added.

server {
    listen   80;
    server_name sourcecodebean.com;

    index index.php index.html;
    root /path/to/web/root;

    location ^~ /secret-dir/ {
        auth_basic            "Restricted";
        auth_basic_user_file  /path/to/htpasswd;
    }

    location / {
        try_files $uri $uri/ /index.php?q=$uri&$args;
    }

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        include /etc/nginx/fastcgi_params;
        fastcgi_pass  127.0.0.1:9200;
        fastcgi_index index.php;
        fastcgi_param  SCRIPT_FILENAME  /path/to/web/root$fastcgi_script_name;
    }
}

Woho! All done!

Peter

Leave a Reply

Your email address will not be published. Required fields are marked *