Search code examples
wordpress.htaccessenvironment-variables

if function in htaccess using env


I'm using phpdotenv package to setup env in wordpress project

env file

ENVIRONMENT=production
DB_NAME=
DB_USER=
DB_PASSWORD=

I need to add if function in htaccess to do the https redirection based on ENVIRONMENT.

currently I could not get env value in htaccess.


Solution

  • "phpdotenv" is a PHP package. It processes the .env file too late for the variables to be accessible from .htaccess. (.htaccess is processed before PHP gets to handle the request.) So, what you are trying to do is not possible.

    You would need to do it the other way round. ie. Set the environment variables in .htaccess (or preferably the server config), which will then be accessible to both PHP and .htaccess.

    I need to add if function in htaccess to do the https redirection based on ENVIRONMENT.

    There are often other elements of the request that can be used to determine whether you are on production or not. eg. the requested hostname, server IP address, installed module, existence of a specific file etc. Although this is more commonly achieved by setting an env var (or Defineing a "true" server var) in the main server config and checking for this (or absence of this) in .htaccess.