Apache: basic authentication before rewriting

I have apache in an interface that redirects a request using a rewrite rule. I have to put basic authentication before redirecting the request, so I put this in the configuration file:

<VirtualHost *:443> ServerAdmin xxxxxx DocumentRoot /var/www/html/ ServerName xxxxxxx RewriteEngine on ErrorLog logs/error.log CustomLog logs/access_log common <Directory /var/www/html/> AuthType Basic AuthName "Restricted Files" AuthUserFile /etc/httpd/conf/tag.pwd Require valid-user RewriteRule ^/(.*) http://xxxxxx:xxx/$1 [P,L] </Directory> </VirtualHost> 

But does not work.

Any suggestions?

+7
apache mod-rewrite basic-authentication
source share
3 answers

I decided to set a rewrite condition and rewrite the rule outside the Locatio directive:

 <Location /> AuthType Basic AuthName "Restricted Files" AuthUserFile /etc/httpd/conf/tag.pwd Require valid-user </Location> RewriteCond %{LA-U:REMOTE_USER} !^$ RewriteRule ^/(.*) http://xxxxxx:xxx/$1 [P,L] 

thank you very much h0tw1r3 for the suggestion

* Keep in mind that Location directives work with URLs, not directories. This means that if someone creates an alias for the document root, they bypass these authentication rules completely. (See http://httpd.apache.org/docs/2.0/mod/core.html#location for more details.)

+5
source share

In general, Apache rewrites the phase prior to the authorization phase, so your code does the rewriting without even asking for user authentication.

You can get around this with the LA-U:REMOTE_USER variable LA-U:REMOTE_USER . A preface to your RewriteRule with a condition that looks ahead ("LA") to the authorization phase:

 RewriteCond %{LA-U:REMOTE_USER} !^$ RewriteRule ^/(.*) http://xxxxxx:xxx/$1 [L] 

See notes on this at http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritecond

As other posters note, it is also better to take RewriteRule directives from a block so that they are more reliable.

+10
source share

Refresh . An implicit catalog rule ensures that validation is always required before overwriting. It has been found that various combinations of apache modules change behavior, so the accepted answer may not always work.

 <Location /> AuthType Basic AuthName "Restricted Files" AuthUserFile /etc/httpd/conf/tag.pwd Require valid-user </Location> <Directory /documentroot> RewriteCond %{LA-U:REMOTE_USER} (.+) RewriteRule (.*) http://xxxxxx:xxx/$1 [P,L] </Directory> 
+2
source share

All Articles