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!

Posted in Hosting at November 8th, 2008. Trackback URI: trackback Tags: , , Written by: 

2 Responses to “Password protecting folders with nginx gotcha”

Hey,

Thanks a lot for this post, helped me clarify how to use this nginx directive.

A small correction though. On the Apache section you should replace

1
<Location /secret>

with

1
<Directory /secret>

.

Thanks again.

JuanNo Gravatar on January 15th, 2009 at 5:32 pm

Hi Juan,

Glad i could help!

I see that your code got all black and I will fix that.

I normally use Directory when using Apache but i could not find that functionality in Nginx so I wrote the post to compare similar settings in apache/nginx. My intention where not to fool anyone that Nginx’s Location is the same a Directory in apache.

I will have a second look if I can find something similar in nginx.

Thanks for your comment!

/mathias

Mathias StjernströmNo Gravatar on January 15th, 2009 at 8:50 pm

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

pastbedti.me is using WP-Gravatar