Using apache config and htaccess to dynamically set config vars for dev and production

后端 未结 1 1418
长发绾君心
长发绾君心 2021-02-08 00:40

Short Summary

I need to be able to set an environment variable in the Apache site config that defines if the site is dev, beta or production.

The htaccess file

1条回答
  •  情深已故
    2021-02-08 00:59

    You're basically right. You can set an environment variable using SetEnv:

    SetEnv ENVIRONMENT_TYPE "DEV"
    

    Additionally, given that htaccess is parsed from server configuration down through the relevant directories until the directory that Apache thinks the request can be served from, you can use previously defined environment variables in other htaccess files.

    However, you can't combine/concatenate environment variables, you can only use the SetEnvIf directive to generate environment variables based on the value of other environment variables.

    Additionally, within a SetEnvIf directive, you can only inspect environment variables that have also been created by SetEnvIf:

    E.g. /etc/apache2/sites-enabled/001-project

    # This has to be created by SetEnvIf, I've set the regex to match
    # anything as we want the environment variable set always
    SetEnvIf Host .* ENVIRONMENT_TYPE "Prod"
    
    # Alternatively you could do:
    SetEnvIf Host prod\.domain\.com ENVIRONMENT_TYPE "Prod"
    SetEnvIf Host dev\.domain\.com ENVIRONMENT_TYPE "Dev"
    SetEnvIf Host (www\.)?domain\.com ENVIRONMENT_TYPE "Live"
    

    And in /www/example.com/.htaccess

    SetEnvIf ENVIRONMENT_TYPE "Prod" DB_USER="test"
    SetEnvIf ENVIRONMENT_TYPE "Prod" DB_NAME="database"
    SetEnvIf ENVIRONMENT_TYPE "Prod" DB_PASS="passwd"
    SetEnvIf ENVIRONMENT_TYPE "Live" DB_USER="live"
    SetEnvIf ENVIRONMENT_TYPE "Live" DB_NAME="database"
    SetEnvIf ENVIRONMENT_TYPE "Live" DB_PASS="passwd"
    

    And in /www/example.com/prod/web/sam/.htaccess you can use the IF, Else and ElseIf directives:

    AuthName "Admin Area"
    AuthType "Basic"
    
        AuthUserFile "/www/example.com/prod/web/sam/.htpasswd"
    
    
        AuthUserFile "/www/example.com/beta/web/sam/.htpasswd"
    
    AuthGroupFile "/dev/null"
    ErrorDocument 404 /sam/error.shtml    
    
        Require valid-user
    
    

    Then in your PHP you can access the environment variables using getenv() or:

    echo $_SERVER['ENVIRONMENT_TYPE'], "\n";
    $db_user = $_SERVER['DB_USER'];
    

    0 讨论(0)
提交回复
热议问题