Apache: Rewrite URL to another host

This cryptic title has all to do to avoid CORS warnings in your browser...

CORS

CORS means Cross Origin Resource Sharing and is a mechanism implemented in web browsers to prevent cross site scripting attacks.

Sometimes it is necessary to offload a specific task to a different server. However if you just try to implement calls to a different (sub)domain you will be greeted with lots of warnings and basically things will not work.

So how to integrate that chat server (ejabberd) or that Node.js thingy you just built? Easy, just add a rewrite rule to your vitual host settings. So if I wanted to redirect BOSH traffic from a webchat app to the Jabber server I can add the following rule:

<VirtualHost>
RewriteEngine On
RewriteRule ^/http-bind(.*) http://chat.someotherhost.com:5280/http-bind$1 [P,L]
</VirtualHost>

This rule means that all traffic to http://myhost.com/http-bind* will be redirected transparently by Apache to port 5280 at someotherhost.com.

Attempt to make remote request from mod_rewrite without proxy enabled

This warning will show up in your logs if you forget to enable the mod_proxy and mod_proxy_http modules. The rewrite rule describes above uses these modules as the [P] flag implies the request need to be routed as a proxy request. Enable them as root using:

a2enmod proxy
a2enmod proxy_http
service apache2 restart

The redirect rule should now be working as it should.

This article is my 17th oldest. It is 222 words long, and it’s got 0 comments for now.