Wednesday, February 24, 2010

Serving external content from your own domain with Apache mod_proxy and mod_rewrite

Ok so you want to serve images from your Service provider but you have an SSL site or simply you just want for the sake of uniformity to serve those images from your own domain.

- Oh boy!,  someone says, we need to build a python script that uses curl and download the images, that will take a while ... and bandwidth.
- OK we can cache, said a tech guy.
- Project is then delayed? freaked out the PM
- We need to negotiate ASAP, said the BA while running to his desk to write an email.
- ...

How many solutions a problem might have? Commonly more than one. What we need here has a name and actually a Pattern Name. We need a proxy, and apache has a proxy module, and that can be integrated with the rewrite module and so we can happily serve any image from our own domain even though the resource is located in an external server.

So in the apache conf file for the particular Virtual Host we include a rewrite rule:
<VirtualHost *>
     #In production systems comment the below two lines
     RewriteLogLevel 3
     RewriteLog "logs/"

     <Directory "/my/virtual/host/docroot/directory">
        RewriteRule (.*) [P,L]
We hit Bad luck, it does not work and from the log file we see:
File does not exist: proxy:

Let us take a look at Server libraries
httpd -l
 Voila, mod-proxy support is not enabled. So after we recompile apache with support for mod-proxy:
./configure --prefix=/usr/local/apache --enable-so --enable-rewrite=shared --enable-ssl=shared --enable-proxy --enable-proxy-connect  --enable-proxy-http
make install

We do get what we expected (mod_proxy.c) and our image is showing up even though it does not exist in our domain but in the external server.

No comments: