BrunoMiranda.com

Personal Blog about Technology, Software Engineering, Design & More

Password protect a folder in nginx

Posted on October 29, 2007 at 06:01 PM

What you would normally do in apache with an .htaccess file, nginx requires a different approach.

In sites-enabled, edit your site’s config file by adding the following inside the server block

location = /secret-folder {
  auth_basic            "Restricted";
  auth_basic_user_file  /usr/nginx/htpasswd;
}

Make sure you create a htpasswd file in the correct location.

htpasswd -b htpasswd NewUser NewPassword

Very useful nginx wiki.

Good Luck!

Tags: nginx
Hierarchy: previous, next

Comments

There are 6 comments on this post. Post yours →


Thanks Bruno, short and sweet.

Denis

There is an error in your example. location = /secret-folder {…} will not protect the content of the folder, you need to use location ^~ /secret-folder {…}

See http://wiki.codemongers.com/NginxHttpCoreModule#location for the detailed explanation.


Great,

Thanks Bruno.


“short and sweet” and will not work for /secret-folder/secret-file.html because of “=” sign

try this:

location ~ ^/secret-folder { auth_basic “Restricted”; authbasicuser_file /etc/nginx/htpass; }


I think this protects multiple directories…

location ~ /(somewhere/.|delta/.) {

Not exactly sure what the “.*” does.

I’m having an issue where blah.com/somewhere/ is protected but blah.com/somewhere has strange results.

I’m about to try this…

location ~ /(somewhere/.|somewhere|delta/.) {


Here is how I protect my backend

location ^~ /backend { auth_basic “Restricted”; authbasicuser_file /home/dgd.gudasoft.com/.htpasswd;

    set  $script     $uri;
    set  $path_info  "";
    if ($uri ~ "^(.+.php)(/.+)") {
      set  $script     $1;
      set  $path_info  $2;
    }
    fastcgi_pass   127.0.0.1:9000;
    include        fastcgi_params;
    fastcgi_param  PATH_INFO          $path_info;
    fastcgi_param  SCRIPT_FILENAME  /home/dgd.gudasoft.com/web$script;
    fastcgi_param  SCRIPT_NAME       $script;

}

not very smart but extreamly quick!

Post a comment

Required fields in bold.

 

Visit the Archives →