Environment detection with .htaccess
Published
Updated
Target rules by environment context.
One `.htaccess` file in git reaches every environment. Apache on fortrabbit reads the ENV vars of the environment, so an `<If>` block can apply rules in production or staging only, without a second file.
ENV vars in Apache
Apache gets the same ENV vars as PHP: the custom ones from the dashboard and the platform ones such as FORTRABBIT_ENVIRONMENT_NAME, which holds the name of the environment as it reads in the dashboard, for example production. A change in the dashboard takes about 60 seconds to reach Apache.
Apply rules in one environment
The <If> block takes an Apache expression. env() reads an ENV var:
<If "env('FORTRABBIT_ENVIRONMENT_NAME') != 'production'">
Header set X-Robots-Tag "noindex"
</If>
This keeps search engines away from every environment except production. The condition reads the name as it shows in the dashboard. Locally, the variable is not set, so != is true there as well.
Use a custom ENV var
A custom ENV var decouples the rule from the environment name. Set it in the dashboard:
PROTECT_SITE=true
Then check it in .htaccess, here for HTTP auth on a staging environment:
<If "env('PROTECT_SITE') == 'true'">
AuthType Basic
AuthName "Restricted area"
AuthUserFile /data/www/.htpasswd
Require valid-user
</If>
In RewriteCond
mod_rewrite reads ENV vars with %{ENV:…}. This redirects the default domain to the primary domain in production only:
RewriteEngine On
RewriteCond %{ENV:FORTRABBIT_ENVIRONMENT_NAME} =production
RewriteCond %{HTTP_HOST} \.frbit\.app$ [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]