How to password-protect a Django site with .htaccess
I recently had to password-protect a subdirectory of my site and found existing documentation on this to be wholly inadequate -- at least applied to sites utilizing Apache and Django. The problem is that to password-protect a subdirectory, one must write rules in an .htaccess file residing in the parent directory. Since Django projects use a hand-written URL dispatcher, the directory structure of the resulting Web site doesn't reflect the structure of the internal storage system.
Fortunately, the solution is simple. Instead of writing your Apache directives in an .htaccess site, write them where your Django configuration resides. This will typically be your httpd.conf or site-specific configuration files you've created in your Apache sites-available/ directory.
I made a copy of my existing configuration under the location "/subdirectory," and added the following directives.
<Location "/subdirectory"> AuthType Basic AuthName "My Secret Site" AuthUserFile "/path/to/.htpasswd" Require user username ... </Location>
Be sure to use the "htpasswd" command on Unix to make an .htpasswd file in a directory on your server. Change the path in my sample above to where you store the file. Be sure that "username" matches the username you create using htpasswd.
That's it. If you know how to do this without duplicating my existing configuration, please post how to do so in the comments. That would be much appreciated.