Freebsd – Header set Access-Control-Allow-Origin not working with mod_rewrite + mod_jk

apache-2.2freebsdhttp-headersmod-jkmod-rewrite

My first question on here on SF so please forgive me if I manage to bork the post. 🙂

Anyways, I'm using mod_rewrite on one of my machines with a simple rule that redirects to a webapp on another machine. I'm also setting the header 'Access-Control-Allow-Origin' on both machines. The problem is that when I hit the rewrite rule, I loose the 'Access-Control-Allow-Origin' header setting.

Here's an example of the Apache config for the first machine:

NameVirtualHost 10.0.0.2:80
<VirtualHost 10.0.0.2:80>
   DocumentRoot /var/www/host.example.com
   ServerName host.example.com
   JkMount /webapp/* jkworker
   Header set Access-Control-Allow-Origin "*"
   RewriteEngine on
   RewriteRule   ^/otherhost  http://otherhost.example.com/webapp [R,L]
</VirtualHost>

And here's an example of the Apache config for the second:

NameVirtualHost 10.0.1.2:80
<VirtualHost 10.0.1.2:80>
   DocumentRoot /var/www/otherhost.example.com
   ServerName otherhost.example.com
   JkMount /webapp/* jkworker
   Header set Access-Control-Allow-Origin "*"
</VirtualHost>

When I hit host.example.com we see that the header is set:

$ curl -i http://host.example.com/
HTTP/1.1 302 Moved Temporarily
Server: Apache/2.2.11 (FreeBSD) mod_ssl/2.2.11 OpenSSL/0.9.7e-p1 DAV/2 mod_jk/1.2.26
Content-Length: 0
Access-Control-Allow-Origin: *
Content-Type: text/html;charset=ISO-8859-1

And when I hit otherhost.example.com we see that it too is setting the header:

$ curl -i http://otherhost.example.com
HTTP/1.1 200 OK
Server: Apache/2.0.46 (Red Hat)
Location: http://otherhost.example.com/index.htm
Content-Length: 0
Access-Control-Allow-Origin: *
Content-Type: text/html;charset=UTF-8

But when I try to hit the rewrite rule at host.example.com/otherhost we get no love:

$ curl -i http://host.example.com/otherhost/
HTTP/1.1 302 Found
Server: Apache/2.2.11 (FreeBSD) mod_ssl/2.2.11 OpenSSL/0.9.7e-p1 DAV/2 mod_jk/1.2.26
Location: http://otherhost.example.com/
Content-Length: 0
Content-Type: text/html; charset=iso-8859-1

Can anybody point out what I'm doing wrong here? Could mod_jk be part of the problem?

Best Answer

I've successfully used:

SetEnvIf Origin "http(s)?://(domaine1\.com|domain2\.com)$" AccessControlAllowOrigin=$0
Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin

from http://www.cameronstokes.com/2010/12/26/cross-origin-resource-sharing-and-apache-httpd/