Conditions in Apache

吃可爱长大的小学妹 提交于 2019-12-31 04:20:09

问题


I have KOHANA_ENV environment var set to DEVELOPMENT for example. Now there is a set of rules I'd like to apply only if that var is set to PRODUCTION (turn on mod_deflate, set expires headers defaults, turn off ETags, etc.), like:

if (KOHANA_ENV == PRODUCTION) {
    // .. do stuff
}

Is there a way to do this on Apache level at all or it's better to have two conf files?


回答1:


I do it with the help of the great module mod_macro.

Let's say you have in /etc/apache2/envvars (for a Debian-like distribution it's the place to store apache environnement variables):

#export KOHANA_ENV=PROD
export KOHANA_ENV=DEV

Where you [un]coment depending on production or development.

In the other side you have your VirtualHost, or just a part of it defined with a macro. Macro is the way to write a generic configuration part with some variables. I use it for complete Virtualhosts but here's an example with just a part of a VirtualHost. We'll use the environnement variable to decide which macro to use (keyword Use):

<Virtualhost *:80>
    ServerName foobar.com
    #(...)
    Use EnvStuff_${KOHANA_ENV} /tmp
    #(...)

Here the macro takes an argument (tmp directory path) it's not an obligation.

Then you should only define 2 different macro where the environnement variable is part of the macro name EnvStuff_PROD & EnvStuff_DEV:

<Macro EnvStuff_PROD $tmp>
    <IfModule mod_expires.c>
        # Enable expirations.
        ExpiresActive On
        # Cache all files for 2 weeks after access (A).
        ExpiresDefault A1209600
    </IfModule>
    <IfModule mod_headers.c>
       Header set MyHeader "Hello this is PRODUCTION envirronment. It took %D microseconds for Apache to serve this request."
        # Serve gzip compressed CSS files if they exist and the client accepts gzip.
        RewriteCond %{HTTP:Accept-encoding} gzip
        RewriteCond %{REQUEST_FILENAME}\.gz -s
        RewriteRule ^(.*)\.css $1\.css\.gz [QSA]
        #(...)
    </IfModule>
    php_admin_value upload_tmp_dir $tmp/upload
    #(... other php settings for production)
</Macro>
<Macro EnvStuff_DEV $tmp>
    <IfModule mod_expires.c>
        # Enable expirations.
        ExpiresActive Off
    </IfModule>
    <IfModule mod_headers.c>
       Header set MyHeader "Hello this is DEVELOPMENT envirronment. It took %D microseconds for Apache to serve this request."
    </IfModule>
    php_admin_value upload_tmp_dir $tmp/upload
</Macro>

In these examples you can checkl headers in responses and you'll see easily if it worked for you.

Be careful, if the environnement variable is not set well, you'll get some problems, maybe you can create a macro EnvStuff_ as well :-)



来源:https://stackoverflow.com/questions/6343621/conditions-in-apache

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!