Search code examples
apachemod-rewriteenvironment-variablesapache2reverse-proxy

Apache Reverse Proxy - config not setting env variable correctly


I'm having an issue with my Apache2 reverse proxy config.

I have an app running on HTTPS that can be access directly by https://my-application:443 and indirectly through the reverse proxy on https://proxy:443/custom-app.

I'm trying to only allow admin users access to the management parts of my system (e.g. https://my-application:443/management/settings).

However when I try to set an env variable (USER_GROUP) that's initially set to 'users' but changes to 'admins' if it meets certain conditions, it doesn't re-set the var.

Can anyone please point out what I'm doing wrong?

<Location "/custom-app">

   SetEnv USER_GROUP users

   RewriteCond %{REQUEST_URI} ^/custom-app/management
   RewriteRule ^(.*) $1 [E=USER_GROUP:admins]

   <RequireAll>
     Require          claim user.groups:/%{ENV:USER_GROUP}
     Require          valid-user
   </RequireAll>

   ProxyPass        https://my-application:443
   ProxyPassReverse https://my-application:443

</Location>

Solution

  • SetEnv USER_GROUP users
    
    RewriteCond %{REQUEST_URI} ^/custom-app/management
    RewriteRule ^(.*) $1 [E=USER_GROUP:admins]
    

    mod_rewrite is processed before SetEnv (mod_setenv), despite the apparent order of directives in the config file. So this is effectively initialising the env var to admins, which is then being overwritten by SetEnv to users.

    You would need to either use SetEnvIf (mod_setenvif - which is processed much earlier) or even mod_rewrite to initialise the env var. Although there is no need to use mod_rewrite here - this can all be achieved using SetEnvIf only - which would be preferable. (It is not recommended to use mod_rewrite inside <Location> blocks anyway.)

    For example:

    SetEnvIf ^ ^ USER_GROUP=users
    SetEnvIf Request_URI "^/custom-app/management" USER_GROUP=admins
    

    Reference: