regexapachemod-rewriteapache2.4

How to check IF query string exists in Apache


I am trying to check if the query string is not present in the HTTP request then set some headers. I am following this : https://httpd.apache.org/docs/2.4/expr.html

I have tried -

 <If "! %{QUERY_STRING} ">
        Header always set Cache-Control "max-age=120"
  </If>

or

<If "%{QUERY_STRING} -z">
        Header always set Cache-Control "max-age=120"
  </If>

Getting syntax error. Can you pls tell how to do it?


Solution

  • <If "%{QUERY_STRING} -z">
    

    Should be the other way round:

    <If "-z %{QUERY_STRING}">
    

    Or, you could test that it is equal to the empty string:

    <If "%{QUERY_STRING} == ''">
    

    Note that this tests if the query string is "empty", it might still exist. In other words, there could be a lone ? on the end of the URL. In this case, arguably there is a query string, but it is empty.

    If you need to be more strict and test whether there is any query string, even "empty" then check against THE_REQUEST for a literal ?. For example:

    <If "%{THE_REQUEST} !~ '\?'">
        # There is no query string, since there is no "?"
    </If>
    

    (!~ operator does not match the regex.)