Search code examples
.htaccesslocalhostproduction

Htaccess separate for Localhost and Production


How to create an Htaccess which will have a specific and separate code for Localhost and Production. I mean when we work on localhost, it should be work localhost code and in Production it should be load only Production code. So that i can use one Htaccess for Local and Production and it will save lot of time. Following is the model i would like to implement. It would be much appreciate anyone can help on this. Because i spend lot of time on it and not found any good approach on this. Thanks in Advance!

<Localhost>
---localhost code goes here 
---it should be only work in localhost and not at all in Production
</localhost>

<Production>
---production code goes here 
---it should be only work in Production and not at all in Localhost
</Producton>

Solution

  • Most of the code in .htaccess should be the same on local and production. (Otherwise, how do you test it?)

    However, one of the cleanest ways to separate directives between servers is to Define (requires Apache 2.4) a variable in the server config of one of the servers (eg. the development machine):

    Define DEVELOPMENT
    

    This can be defined anywhere in the server config (not .htaccess), but is always seen as global to the server, regardless of whether it is defined inside a <VirtualHost> container or not. You do not need to specify a value (2nd) argument since the <IfDefine> directive (see below) does not check this. As always, whenever you make changes to the sever config you'll need to restart Apache for the changes to take effect.

    And reference this in .htaccess:

    <IfDefine DEVELOPMENT>
        # Local / development directives only
    </IfDefine>
    
    <IfDefine !DEVELOPMENT>
        # Live / production directives only
    </IfDefine>
    

    The ! prefix tests that the variable is not defined.

    Depending on what type of directives you need to contain you can use an <If> container and check something like the requested hostname (eg. staging.example.com vs www.example.com for the live site). However, <If> containers do not work the same with mod_rewrite.

    Reference: