apache: basic authentication before rewrite

人盡茶涼 提交于 2019-11-30 03:41:20

问题


I have an apache in frontend that redirect a request via a rewrite rule. I have to put a basic authentication before redirect a request, so I put this in the config 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 doesn't work.

Any suggestions?


回答1:


In general, Apache does the rewrite phase before the authorization phase, which is why your code performs the rewrite without ever asking for user to authenticate.

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

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

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

As other posters point out, it's also better to take the RewriteRule directives out of the block so they are more reliable.




回答2:


I solved putting the rewrite condition and rewrite 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]

many thanks to h0tw1r3 for the suggestion

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




回答3:


Update: Implicit directory rule ensures validation is always required before the rewrite is done. Found that different combinations of apache modules changed the behavior, thus 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>


来源:https://stackoverflow.com/questions/2606435/apache-basic-authentication-before-rewrite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!