Restrict Access to Nginx Web Files with Auth_Basic

Easily restrict access to hide sensitive data, admin areas & other web pages using the Nginx web server’s Auth_Basic security module & the htpasswd password creation tool.
What we’re gonna do, essentially, is to create a password file, then adapt a site’s virtual host file. That done, Nginx knows there’s a point of restricted access, and knows where to look for the corresponding password so that, when we surf to the appropriate URI, it can prompt us to log in or hack off.
Dead simple, pay attention, here goes ..
Setup Unmanaged VPS: The Ubuntu-Nginx Guide
Take your virtual private server from zero to hero
.. from blank box to cute-as server ..
with this easy-to-follow copy/paste guide.
22+ parts with video, here’s the index.
Password Protect a Web Directory
This is the most common requirement so that, for instance, you can protect an administrative zone, else maybe double up security for a handy web client like phpmyadmin or a webmail application.
Create the Password File
First up, download this password-creation tool that we’re pinching from the chaps at Apache. It’s quite a nice program because its quick to use and encrypts your token:-
.. or if you did all that bashrc shortcut stuff, be lazy like me:-
Now cd to your /home/user folder:-
.. and type:-
htpasswd Directives, er, Deconstructed
- htpasswd is the Apache program we run to adapt or, in this case, to create the security file
- -c means create a new file
- .htpasswd is the name of the file but it can be anything you like. The . means it’ll be a hidden file, although it doesn’t have to be
- some-name can be swapped for some moniker of the person for whom you wish to provide access. That name needn’t be a system user, ie you don’t have especially to adduser
.. you’ll be asked to give and confirm a password.
Add More Users Using htpasswd
You may not need to do this, but for educational purposes, why ever not. Change directory, into the same as the password file:-
.. and adapt the password file ..
.. there’s no -c because we’re not creating a new file, instead adapting an existing one. And
another-name is, well, just that.
You’ll be asked to give and confirm a password.
Let’s take a peek:-
.. and we see, pretty much ..
Relocate the Password File
So. A file has been created in your /home/user directory. It can live there. It can live anywhere you like, but it shouldn’t be amongst the actual web files. I’m inclined to move it, like so:-
.. so it sits with my Nginx config and virtual host files and directories. For some folks (if you installed Nginx using apt-get or aptitude, rather than wget’ting the source code which you should have done really but never mind), that may instead be at a location like /var/www/I-forget-exactly.
Adapt the Virtual Host File
If you’ve not bothered with separate vhost files, instead bunching your site configs all in the nginx.conf, pop it open:-
For those less messy types who have a virtual host website configuration file, well done, let’s crack that open instead:-
Either way, within the file you’ll see the syntax specific to your website, looking something like this:-
What we have here, by way of a quick recap is ..
.. the first server block, basically a rewrite rule so that when someone types in www.whatnot.com, they’re redirected to whatnot.com.
.. the top of the key server block, those www types having been redirected to non-www, which contains the core ruleset. 80 is the port Nginx listens on, and the rest pretty clear.
.. the location block ..
- root defines the path to the site, on the server. (Remember, our web files are in the public folder if you followed this guide)
- index says for Nginx to look out for either an html or, if present, a php file instead
- **** Nothing, yet. But this is where we’ll add our restricted access details, so there’s a clue ****
- some WordPress-specific stuff, which we added in the WordPress-Nginx guide, but which you can ignore if you don’t use WP
.. some fastCGI link-ups, which I’ll be talking about more in a future how-to guide. And we close the server block with the final }.
Now then, no excuse for not putting the protected folder info in the right place. The syntax is:-
- location ^~ /path/to/hiddenFolder { We’re creating another location block, this time cascading within the pre-existing one, and are specifying the folder and its content that we wish to protect, in this example called /hiddenFolder. Because we’re nestled within the original location block, this block inherits the original root, recorded originally. Thus, when someone tries to access the server’s /home/USERNAME/public_html/MYDOMAIN.com/public/path/to/hiddenFolder directory, aka http://MYDOMAIN.com/path/to/restricted.html, they’ll be prompted for a username and password
- auth_basic “Restricted Access”; This is calling the auth_basic module that does the grunt work, while also displaying “Restricted Access”, or “Whatever You Want For That Matter” on the password request dialogue box
- auth_basic_user_file /usr/local/nginx/.htpasswd; Calls our new password file
- } Closes the child location block
Save the file. Restart Nginx:-
.. or n2r if you followed the bashrc thing (if you did, by this time I’ll bet you’re pleased about that!)
Checking the Restricted Access Folder
Mkdir the path to the folder requiring protection, if you’ve not already done so.
Then head over, logging in with using the username and password you gave, to:-
Protect a Specific File
Alternatively, maybe you want to protect just a file, some specific document, a media item, whatever. This second option will do just that, but will protect nothing except a precise path. That can be handy if you want everything visible, bar a special item.
The method is the same as for folders, bar a few characters. Create the password file as before, then adapt the virtual host syntax. We had:-
Change it to:-
.. of course, it works for anything, not just pdf’s.
Advanced Restricted Access
For most of us, the above methods are what we want, and the equivalent of what we’ve been used to, using something horrible like cPanel.
However, there are more advanced techniques one can employ, such as restricting access to a specific IP or IPs, and I’ll be covering that, and other diversions, in a follow-up to this post.
Fix a feed for updates. You know it makes sense.
Here’s the index, which doubtless will expand ..
Setup Unmanaged VPS: The Ubuntu-Nginx Guide
Take your virtual private server from zero to hero
with this easy-to-follow copy/paste guide.
“My local PC runs Windows” Show me for Linux
“My local PC runs Linux” Show me for Windows
22+ parts with video, here’s the index ..
-
Setup Unmanaged VPS: The Ubuntu-Nginx Guide
Introducing vpsBible’s how-to guide for setting up a super-charged unmanaged VPS featuring Ubuntu and Nginx.
-
VPS (Virtual Private Server) vs Shared vs Dedicated
Before getting stuck in, let’s compare the web host types in detail and weigh up the differences between managed & unmanaged VPS.
-
Set Up a VPS Linux Distribution
Opening a VPS hosting account, we’ll choose, configure & launch a Linux server ‘distribution’.
-
Set Up Command Line Interface (CLI) using PuTTY
Now we’ve got a server to play with, we’ll connect to it, using the ’ssh’ protocol for a super-secure link.
-
Create a Linux User & Set Permissions
Initially you’ve logged into your remote Linux machine as ‘root’. We’ll add you as a user now, with root or SuperUser permissions.
-
Encrypt Data with OpenSSH & Auto-Login with PuTTY
Now we can use ‘authentication keys’ to shore up our connection while simplifying login to an automated, password-free yet secure process.
-
Harden the Secure Shell (SSH) & Create a Firewall
The final security step: galvanizing the OpenSSH protocol and setting up an ‘iptables’ firewall. Now the server is rock ruddy solid.
-
Edit bashrc for User-Friendly Linux, plus System Updates
We use the terminal a whole lot so let’s cut ourselves a break and create some command shortcuts, then update the server.
-
Add a Domain Zone to Your VPS
To make your server aware of yourDomain.com you’ll need a few ‘DNS’ records. Damn this is simple I’m practically asleep!
-
Prepare Linux Server for Email with Postfix
In order to send and receive email from our web applications we’ll install some software and tweak the ‘RDNS’ record.
-
Install PHP5 & MySQL – The One-Stop FastCGI Index Page
Add PHP5 & MySQL, but which FastCGI method is best? Here’s the benchmarking, 4 ways to install/compile, add caching modules & more.
-
Nginx (better than Apache) Web Server
Let’s install this supersonic web server, tweaking its file structure & adding default configuration files.
-
Setup FileZilla for Secure FTP (SFTP)
There’s FTP, and then there’s ‘Secure FTP’. We’ll set up FileZilla using SFTP – and those authentication keys – for secure file transfers.
-
Serve Multiple Sites & Blogs with Virtual Hosts
We want a website folder structure, some permissions, some site-specific configuration files and, hey, we’ll hook up ‘FastCGI’.
-
Adding Sub-Domains with Nginx
Need a sub-domain? If you do, here’s how to add subDomain.yourSite.com with an ‘A record’ and a configuration file.
-
Integrate A CMS Like WordPress, WP MU, Drupal etc
For those of you wanting to use a specific content framework, such as a CMS, blogging or forum software, pop in here and we’ll sort that out.
-
Google Apps for Domain-Specific Email
GA’s free Standard Edition for catchall webmail – POP-ping or IMAP-ped to your desktop client – saves precious server resources for your webs.
-
Moving Day! How to Move Your Blog or Site
Nearly there. Here’s the web site or blog migration guide, relocating to your VPS with minimal or no downtime.
Manage Unmanaged VPS: Ubuntu-Nginx Administration
Already set it up? We’d best maintain it then.
Toggle to the .. Ubuntu-Nginx Admin Index
Manage Unmanaged VPS: Ubuntu-Nginx Administration
Maintain your virtual private server with ..
.. cheatsheets, tutorials, tips & guides.
Head back to the .. Ubuntu-Nginx Installation Index
-
Nginx Control Panel: Here’s the Deal
You’re migrating shared-to-VPS and want a GUI like cPanel? No you don’t, not after you read this! What’s more, you don’t need one either.
-
Nginx Control Panel Workarounds
For every control panel module there’s an equivalent (and faster) terminal command. Let’s compare these.
-
Upgrade to Nginx Latest Version with ZERO Downtime
Keep Nginx up-to-date – and optimized for security. This guide shows precisely how *with no missed server requests*.
-
Compile an Advanced Nginx Module Configuration
Need special web server functions? Here’s how to install or upgrade Nginx with bespoke required modules & parameters.
-
Add Web Sites Nginx Cheatsheet
Once you’ve set up your first site, adding more gets easier. Especially when you refer to this. (Let’s face it, I’m just too good to you.)
-
Adding Sub-Domains with Nginx
Rather than add somesite.tld, maybe you want some.subsite.tld? Here’s how to set your A record using a DNS manager and the vhost file for Nginx.
-
Add/Delete MySQL Database from Command Line
Need a database? Want to bin an old db? This tutorial shows you how using the terminal command line console whatnot.
-
Configure phpMyAdmin for Nginx to Maintain MySQL
Rather than have to crunch databases via the command line, we can make life easier by adding this splendid tool to manage them.
-
Backup/Export MySQL DB with CLI & mysqldump
Here’s how to backup a database from the command line using the handy mysqldump utility.
-
Import MySQL Database using Command Line
Import data to a new database with this simple mysqldump guide .. great for reinstating an old backed-up db, for instance.
-
Batch Replace/Delete Data in MySQL Database
Change repetitive db data with a single command. Rather than manually find & alter each instance, isolate the lot & update multiple content.
-
LOST a MySQL Password? How to RESET it
Lost your MySQL password? That’s a bit of a bummer .. or it would be if you didn’t have this new password setup guide, huh.
-
Backup or Upload with Secure Copy SCP (Linux to Linux)
Never mind FTP m8! Save time and download/upload your files using encrypted SCP (secure copy), the #1 Linux-Linux file transfer solution.
-
Backup or Upload with PuTTY PSFTP (Windows/Linux)
Equivalent to the above, how to transfer your files if you’re unlucky enough to be running Windows for your local PC. Not that I’m biased.
-
*USEFULLY* Park A Spare Domain with Nginx
Got a spare domain name sat around doing nothing? Put it to some use, have it point its traffic at your primary domain. Here’s the deal ..
-
Password Protect Nginx Web Files/Directories
Maybe you want a hidden website directory, say, for projects, or are developing a site and want it off-limits ’till launch day. Top tip ..
-
Redirect Web Pages with Nginx Rewrite Rule
Here’s the syntax to point a site or blog to another domain. That way, for instance, traffic from a passive site benefits an active one.
-
Nginx Error & Access Logs
Need to troubleshoot some error, or want to find out who’s trying to hack your site? Here’s a start .. those tell-tale logs.
-
Subversion for Easy CMS Updates ie WordPress/Drupal/etc
A brief introduction to install and know about the power of Subversion, the version control system to keep scripts and platforms up-to-date.
-
You Tell Me …
Something missing? Probably. Let me know what you’d like included. And if it’s listed below, shout out anyhow and I’ll try to bump it.
Nginx Admin: In the Works ..
This lot’s marked for addition already:-
- Setup or Edit DNS using Bind
- Network Tools Troubleshooting Guide
- The Comprehensive Permissions Guide
- Configuring Nginx Rewrites
- Custom Website Error Page
- Setting up Cron Jobs
- Rsync for Incremental Remote-to-Local Backup
- Cron & Rsync for Automatic Backup
- Cron & mysqldump for Auto DB Backup
- Safeguard Bandwidth with Hotlink Protection
- Block Access with Nginx’ IP Deny
Got a Question? Want to Comment?
This site has no comments system. We've got a better system!
Please use the link at the top of the post and goto this topic's forum thread:-
- to help build community
- for a superior knowledge base
- to keep info in one place, not diluted between forum & comments.
For those posts ported from Guvnr.com (pre-Feb/2010), archive comments remain.
Handy info from these comments is in the process of being ported to the forum and attributed to the original author.
If you think this idea sucks, let me know.
Thank you.






















markie December 6th, 2009 at 3:43 pm
When i try to password protect a directory like above, Nginx gives me a 404 error after verifying the password? any ideas?
the_guv December 7th, 2009 at 10:01 am
@markie .. checked you file permissions?