Password protecting folders with nginx gotcha
Today I was playing with nginx’s flv module. The page I made where private enough to password protect so i thought it would be great opportunity to learn how to do this with nginx.
When password protecting folders with apache I usually do something like this
1 2 3 4 5 6 | <Location /secret> AuthType Basic AuthName "Restricted Directory" AuthUserFile /usr/local/apache/.htpasswd Require user billg </Directory> |
This code protects the folder named secret and everything below it.
Ok, get back get to nginx already!
Nginx also have a location module and this is how i first started out.
1 2 3 4 | location = /secret { auth_basic "Restricted"; auth_basic_user_file /etc/nginx/htpass; } |
First this seemed like a good idea. Accessing /secret got me authenticate and thats good. BUT! Accessing files below /secret like /secret/image.gif skipped authentication.
Using that equal sign was a big mistake. Equal sign matches exactly that string and nothing else.
To get this example working the way i want (just like the apache example) we have two ways to go.
1. We dump the equal sign,
2. We change the equal sign to a regular-expression sign (~).
Before choosing 1 or 2 you should know that when choosing 1. Rules with regular expressions and any longer conventional blocks will be matched before your rule. So my suggestion is to use a regular expression match so that nginx halts the search.
Alt 1.
1 2 3 4 | location /secret { auth_basic "Restricted"; auth_basic_user_file /etc/nginx/htpass; } |
Alt 2.
1 2 3 4 | location ~ ^/secret { auth_basic "Restricted"; auth_basic_user_file /etc/nginx/htpass; } |
Happy password protecting!
Cheers!
