Super Simple NGINX Security

This assumes you’ve got both NGINX and apache2-utils installed (for generating your username/password file). It is possible to set up your auth_basic_user_file using other tools for example Htpasswd Generator or by using an md5 Hash Generator and creating a file containing username:password_hash with each username on a separate line. If you’ve got htpasswd installed however it’s definitely quickest and simplest to use that.

Locate your server config

Where you’re looking for this will depend on whether you’re using vhosts or not. If you’re not it will probably be /etc/nginx/sites-enabled/default if you’re using vhosts you should find it somewhere like: /etc/nginx/vhosts/[username]/[site].conf.

Create password file

I like to store the password files away from the web root but close to the site they relate to, so I will usually put them in the [username] folder.

sudo htpsswd -c [filename] [user]

This creates a new file in the current location called and adds a user. You will be prompted to enter your desired password twice to complete the process.

If you want to add another user omit the -c flag as this tells htpasswd to create a new file.

Set up your server conf

Option 1: lock down the whole thing

Inside your server config put the following:

server {
    auth_basic              "Why this bit is locked down"
    auth_basic_user_file    /etc/nginx/vhosts/[username]/[filename]

Option 2: lock down a section of your site

Same as above but wrap the auth section in a location block:

server {
    location /locked {
        auth_basic              "Why this bit is locked down"
        auth_basic_user_file    /etc/nginx/vhosts/[username]/[filename]

Restart* Reload the service

If you don’t do this your changes wont have any effect.

sudo service nginx reload

As Paul pointed out on Twitter you don’t actually need to restart the service to make this work. Reloading is enough.


The official NGINX docs go into more detail about what you can do with HTTP Basic Authentication.

This Stack Overflow answer talks you through the whole thing for a single server instance.


There are no comments yet.

Add a Comment

You can use Markdown to format your comment.

Buy me a coffee Buy me a coffee