Wordpress and .htaccess Password Protected Directories

I tried to make a password protected directory using a .htaccess file earlier today and found out that the root Wordpress .htaccess file causes a little trouble.

The situation looks something like:

  • /
    • .htaccess <- From Wordpress
  • /ProtectedDir
    • .htaccess <- My file
As of Wordpress 2.3.2, its .htaccess file looks like this:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

This lives at the base of Wordpress install, which for me happens to be the root of my web site. The rewrite rule throws any URL that leads to a non-existent file to Wordpress' index.php. This lets Wordpress do search engine friendly URLs and custom 404 handling.

The problem here is subtle. In order to do password authentication, the web server needs to serve up a "401 Unauthorized" header and optionally an error document. My server defaults to a specific error document path, but I have not created a document at that path. However, Apache still passes the predefined 401 document path through the rewrite rules in an attempt to use it. Since it doesn't exist, the request gets snagged by the Wordpress rewrite rules and index.php. The end result is that what should have been a 401 page now turns into a 404 and you can't authenticate to the directory.

The solution is simple: override the non-existent, predefined error document path using the ErrorDocument directive in either of the .htaccess files mentioned above.

You have several options. You can either use Apache's default hard-coded string for the error document by specifying:

ErrorDocument 401 default

Or you can use your own hard-coded error string:

ErrorDocument 401 "Unauthorized access"

Or you can create a 401 document and point the server to it like so:

ErrorDocument 401 /401.html

Pick one of those methods and your password authentication should work. Remember, the error document file must exist if you pick the last method.

Note that the same problem can occur with other HTTP error codes, so be on the lookout for other situations where Wordpress might bite you.

Updated Jan. 27 thanks to a suggestion made in this web forum post.