php.htaccessheadermod-headers

How add to .htaccess condition like this?


Need add to .htaccess condition like this:

if (page == '/admin') {
    Header add Test "test"
}

This is not working:

<IfModule mod_headers.c>
    <If "%{REQUEST_URI} == '/'">
        Header add Test "test"
    </If>
</IfModule>

But this working on all pages (logically):

<IfModule mod_headers.c>
    Header add Test "test"
</IfModule>

I know about env=[!]varname, but don't know how use in my case..

I would be glad of any help!


Solution

  • The directive

    <IfModule mod_headers.c>
        <If "%{REQUEST_URI} == '/admin'">
            Header add Test test
        </If>
    </IfModule>
    

    is correct and the header will be added, if the request isn't modified along its way.


    For example, if you have

    <IfModule mod_headers.c>
        <If "%{REQUEST_URI} == '/admin'">
            Header add Test test
        </If>
    </IfModule>
    
    RewriteEngine on
    RewriteRule ^admin$ /index.php [L]
    

    the header will not be set, because the request is modified and will be recognized as /index.php instead. To have the header set on the response, you must change it to

    <IfModule mod_headers.c>
        <If "%{REQUEST_URI} == '/index.php'">
            Header add Test test
        </If>
    </IfModule>
    
    RewriteEngine on
    RewriteRule ^admin$ /index.php [L]
    

    Now the request /admin will be rewritten to /index.php, and the REQUEST_URI processed as "/index.php" and the header is set just before the response is sent to the client, see mod_headers - Early and Late Processing

    The normal mode is late, when Request Headers are set immediately before running the content generator and Response Headers just as the response is sent down the wire. Always use Late mode in an operational server.


    So, depending on how the requests are processed and modified in your environment, you must also modify the condition <If "%{REQUEST_URI} == '...'"> to whatever fits in your environment.