Set environment variables in the apache conf and use them in htaccess rewrites

apache-2.4environment-variables

We have an apache conf defining a bunch of env variables, like so:
/etc/apache2/conf-enabled/env.conf

SetEnv AWS_BUCKET "MY BUCKET"

I would like to use that variable, AWS_BUCKET in my rewrite like so:

RewriteRule ^wp-content/uploads/(.*)$ https://s3.amazonaws.com/%{ENV:AS3CF_BUCKET}/wp-content/uploads/$1 [P]

This bucket changes depending on which server environment we are in, ie – prod, staging, dev, and local.

Which is not working. I read that SetEnv is called after these rewrites so I should use SetEnvIf to set the variable. However, using SetEnvIf still doesn't work because not only cannot not check whether or not AWS_BUCKET is set, but I still couldn't read the variable because is not set until after rewrites and SetEnvIf are called.

SetEnvIf also requires that the needed variable is set in the htaccess file, which I can't do as the point of doing this is to provide a dynamic environment specific solution.

Is there any way to use that set variable from the conf file, or does the variable need to be set as a system wide variable?

EDIT – I unfortunately do not have the ability to add or modify the apache config. The server is run by another department who injects that file during the build and deployment process as a template using provided variables.

So I have to work with what I have access too, which is the web application and the htaccess file. I am unsure they will make any changes to the process for me.

Best Answer

This only works if you use SetEnvIf instead of SetEnv due to the way the directives are processed. So it would need to be set using something like:

SetEnvIf Request_URI ^ AWS_BUCKET="MY BUCKET"