Search code examples
wordpress.htaccessbasic-authentication

.htaccess auth files with wordpress


I'm trying to use basic .htaccess authentication in a subdirectory of the root where Wordpress is installed. The problem is the same as this question. The root .htaccess file that Wordpress uses for permalinks doesn't play nice with a .htaccess file I have in a subdirectory that requires authentication.

However, the solution does not work, and even if it did, I cannot use that solution. This is because Wordpress's htaccess generation overwrites anything I put in that section.

What it generates is:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

And what I would like to stick in that RewriteCond list is

RewriteCond %{REQUEST_URI} !(^/admin(/.*)?$)

Navigating to http://www.example.com/admin should use the .htaccess file in that directory to authenticate the user. eg:

AuthName "Admin Area" 
AuthType Basic 
AuthUserFile "/home/.htpasswd"
AuthGroupFile "/home/.htgroups"
require valid-user

Navigating to http://www.example.com/anywhereelse should redirect to index.php

As it is, I can't even get the RewriteCond shown here to work. It always just shows the 404 page when going into the /admin directory, unless I remove the require valid-user line from the admin .htaccess file. One thing to note is that on that 404 page, the response still contains the WWW-Authenticate header.

So main questions are:

  1. How can I make this work?
  2. Why doesn't it just work as is? Why do I need to exclude the /admin directory?

Solution

  • I've found a solution here. Adding

    ErrorDocument 401 default
    

    To the root .htaccess file outside of the section that Wordpress edits seems to have fixed the issue. I'm not sure if it's the best option though. If there are any better solutions, please feel free to post them.