How to make RewriteCond work with sub-directories needing HTTP authentication

I almost spent 10 minutes trying to figure out a title for this post, as the problem I stumbled upon today is not easy to describe 😉

In a basic Apache environment, I have a rewrite rule routing every incoming request to another listening port. However I want just 1 directory to not be rerouted. So I used this .htaccess configuration:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^myhost.com$
RewriteCond %{REQUEST_URI} !^/dirnotrerouted
RewriteRule ^(.*)$ "http\:\/\/127\.0\.0\.1\:12000\/$1" [P,L]

Therefore every incoming request to http://myhost.com/whatever is redirected to http://myhost.com:12000/whatever and any access to http://myhost.com/dirnotrerouted/whatever is not rerouted. It works.

Now I want to add basic HTTP authentication to one of the directories inside dirnotrerouted. So I created a specific .htaccess file in the restricted directory:

AuthType Basic
AuthName "Restricted area"
AuthUserFile /path/to/.htpasswd
Require valid-user

And now comes the problem: accessing http://myhost.com/dirnotrerouted/restricted is now being rerouted to http://myhost.com:12000/dirnotrerouted/restricted. Problem does not occur for other directories.

And now the solution: specify a 401 error document in the .htaccess file.

ErrorDocument 401 "Unauthorized Access"

AuthType Basic
AuthName "Restricted area"
AuthUserFile /path/to/.htpasswd
Require valid-user

This way your directory is now accessible without being redirected, and is using HTTP authentication.

Muriel

About Muriel Salvan

I am a freelance project manager and polyglot developer, expert in Ruby and Rails. I created X-Aeon Solutions and rivierarb Ruby meetups. I also give trainings and conferences on technical topics. My core development principles: Plugins-oriented architectures, simple components, Open Source power, clever automation, constant technology watch, quality and optimized code. My experience includes big and small companies. I embrace agile methodologies and test driven development, without giving up on planning and risks containment methods as well. I love Open Source and became a big advocate.
Howto, Web development , , , , , , ,

1 comment


Leave a Reply

Your email address will not be published.