Nginx: password protect a directory

Want to help support this blog? Try out Oh Dear, the best all-in-one monitoring tool for your entire website, co-founded by me (the guy that wrote this blogpost). Start with a 10-day trial, no strings attached.

We offer uptime monitoring, SSL checks, broken links checking, performance & cronjob monitoring, branded status pages & so much more. Try us out today!

Profile image of Mattias Geniar

Mattias Geniar, February 24, 2012

Follow me on Twitter as @mattiasgeniar

Nginx is a very powerful webserver, often used as a replacement to Apache for its speed. With Apache, you can very easily protect a directory with a custom username/password by using a .htaccess file. Nginx does not support that (since it’s a performance bottleneck), but it does offer a replacement.

This uses the auth_basic nginx module which is available in nearly every installation of Nginx if you install it via a yum or apt repository.

Create a secure username and password combination

The first step is to generate a secure username and password to use. If you’re out of ideas and want a random password, I offer a password generator for that. At the command line of your server, type the following commands.

# mkdir -p /etc/nginx/passwd.d/
# htpasswd -c /etc/nginx/passwd.d/secure.passwd username

The above will create a directory called “/etc/nginx/passwd.d/” and will next prompt you for a password for the “username” user. If the file already exists, because you’re adding multiple users, you can leave out the -c flag. The “-c” tells the htpasswd command to create a new file. You now have a file outside of your public directory with a secure username and password in it. Never store that secure.passwd file in your webroot, it should never ever be accessible via the webserver document root.

The configuration in Nginx

To secure a directory, use a configuration as follows.

server {
    listen 80;
    server_name mydomain.be;
 
    root /var/www/mydomain.be/htdocs;
    index index.html index.php;
 
    location /securedpage {
        auth_basic "Please enter valid credentials";
        auth_basic_user_file /etc/nginx/passwd.d/secure.passwd;
    }
}

That configuration snippet above will protect the directory “/securedpage” with the username and password you defined in the /etc/nginx/passwd.d/secure.passwd file.



Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.