Enforce https redirect in htaccess depending on environment variable

Enforce https redirect in htaccess depending on environment variable

Ever run into the the problem that you need to have a htaccess redirect on the production system but don't want to have it on your local machine? Usually today it's not that difficult to setup a local self signed certificate any more. But there are still cases like when working with Cordova or Capacitor, which don't allow self signed certificates, where it might be in the way.

And then you might try to change the .htaccess locally but flag it with assume-unchanged in your repository. Just so the next time you switch branches it will be overwritten and you have to change it again.

When I took a step back, I realized that this is not something that should be changed by code, but by configuration. Because it's something that is dependent on your environment. And therefore should be dependent on an environment variable.

Luckily there is a way to setup rewrite conditions depending on an environment variable:

# Force https if ENFORCE_HTTPS is enabled
RewriteCond %{ENV:ENFORCE_HTTPS} ^true
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

When you set an environment variable to ENFORCE_HTTPS=true, you will get an redirect to https. If it is set to false or not exist at all it won't redirect.
This is especially useful if you're working with non pro components like MAMP Pro which doesn't allow you to set environment variables before it's starting within the UI.

You might think you can just put in SetEnv ENFORCE_HTTPS=true in the Additional parameters for <Directory> directive setting. Unfortunately SetEnv will be run after Redirect and therefore has no effect. But there still is a way. There is a envvars file within the MAMP library which is loaded on application start. Putting it in there (and restarting the full MAMP stack) will load it and make it available for the redirect.

Put the following into /Applications/MAMP/Library/bin/envvars:

ENFORCE_HTTPS="false"
export ENFORCE_HTTPS

The file might not exist and you need to create it when you haven't worked with it before.