4

I am runing apache and I am trying to set a header Foo=bar only when the request has a variable "q" on the query string. I would like something like this in my htaccess:

<RequestUri "q=">
    Header set Foor "bar"
</RequestUri>

Of course it does not work. I already tried using "Location" and "LocationMatch" but those are not allowed inside the htaccess. So how can I do that?

2 Answers 2

5

If you are using Apache 2.4, you can do something like this

<If "%{QUERY_STRING} =~ /q=.*?/">
    Header set Foo "bar"
</If>

https://httpd.apache.org/docs/2.4/mod/core.html#if

https://httpd.apache.org/docs/2.4/expr.html#examples

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Sir. One final question: how do I check if a custom header exists? Like <If "%{CUSTOM_HEADER} =~ /.*/"> ?
is it possible to set the header Foo with the value of the query string? example "q=test" --> Foo: test
@user1361529 see my answer below for that.
1

Just to expand on this further if you want to set the header's value dynamically according to the value of the query string you can capture regex groups.

For example if you have a "_locale" variable in your URL and you want to capture its value for a header you could use:

 <If %{QUERY_STRING} !~ m#_locale=([a-z]{2})#">
     RequestHeader set locale "$1"
</If>

(Assuming the value will be two lower case letters.)

This could match "_locale=en" in the query string then copy "en" to header "locale".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.