Set Apache headers conditionally
Asked Answered
D

2

14

I'm working with an apache server, and I'd like to add headers conditionally.

If the URI matches a certain regex, I'd like to add the header Access-Control-Allow-Origin: *. What is a good way to do this?

What I've tried so far:

  1. I added code called by the request handler, using apr_table_add(rq->headers_out, "Access-Control-Allow-Origin", "*"). But it seems like Apache strips the header before sending the response whenever the header Content-Type: application/x-javascript is also set. Is this the wrong way to do it? Why would Apache strip the header?

  2. I've heard mod_headers suggested. Does mod_headers have the capability to place headers based on regex matching with the request URI?

Dromedary answered 21/1, 2014 at 23:3 Comment(2)
how did you solved the problem, did you say that you get the help from some colleagues? Please could you post the answer or the answer of @akond works?Enlace
The answer from @akond worked.Dromedary
K
17
SetEnvIf Request_URI somepartofurl SIGN
Header always add "Access-Control-Allow-Origin" "*" env=SIGN

but this works only if located in the configuration. Placing it into .htaccess won't help.

Konikow answered 22/1, 2014 at 2:34 Comment(3)
Could you explain what this code is doing (syntax, how it works)? When you say "located in the configuration" do you mean in httpd.conf? I'm don't think my module has one. How would I set it up?Dromedary
Figured it out with help from colleagues. Thank you!Dromedary
both SetEnvIf and Header directives are not limited to be located in configuration file only, they work perfectly in directory context, also in .htaccess files. Contrary to what is stated in the accepted answer.Timely
C
12

This should also work (mod_rewrite is required):

RewriteRule ^/en/foo.*$ - [ENV=SET_ACAO:true]
Header set "Access-Control-Allow-Origin" "*" env=SET_ACAO

where ^/en/foo.*$ a regex which is matched against request URL

Coachwork answered 20/2, 2017 at 17:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.