apache: basic authentication before rewrite

后端 未结 4 843
花落未央
花落未央 2020-12-17 21:46

I have an Apache in frontend that should redirect a request via a RewriteRule.

I have to put a basic authentication before the request is redirected, so

4条回答
  •  余生分开走
    2020-12-17 21:59

    
        AuthType Basic
        AuthName "Restricted Files"
        AuthUserFile /etc/httpd/conf/tag.pwd
        Require valid-user
        RewriteRule ^/(.*) http://xxxxxx:xxx/$1   [P,L]
    
    

    There are 2 issues here that will prevent your RewriteRule from doing anything:

    1. You need to enable the rewrite engine inside the container (a directory context). You've (incorrectly) enabled the rewrite engine in the outer container (a virtualhost context) - in which you don't have any mod_rewrite directives. The and containers work in different contexts. If you don't enable the rewrite engine inside the container then the directives will simply be ignored.

      RewriteEngine On
      
    2. When used in a directory context ( and .htaccess) the URL-path matched by the RewriteRule pattern does not start with a slash, since the directory-prefix (that ends in a slash) has been removed. So, you need to remove the slash prefix from the regex, otherwise, it will simply never match in a directory context:

      RewriteRule (.*) http://xxxxxx:xxx/$1 [P,L]
      

      (The ^ prefix on the pattern then becomes superfluous.)

    Summary

    Actioning the above points, this becomes:

    
        AuthType Basic
        AuthName "Restricted Files"
        AuthUserFile /etc/httpd/conf/tag.pwd
        Require valid-user
    
        RewriteEngine On
        RewriteRule (.*) http://xxxxxx:xxx/$1 [P,L]
    
    

    Alternatively, you move the RewriteRule directive outside of the container and use this directly inside the container in which you've already enabled the rewrite engine.

    However, in this context, the mod_rewrite directives will execute before the authorisation directives inside the container, so you will need the additional condition that checks the REMOTE_USER via a look-ahead (ie. LA-U:REMOTE_USER), as mentioned in the other answers.

提交回复
热议问题