mod_rewrite and caching servers
To better learn about the different PEER1 products that I support, I've recently been playing around with the PEER1 Content Delivery Network. The most common CDN set up is to point it at the same webserver you run your main site off of, and then you link back any images or static content back to the caching name instead of the primary name. For example, if your site was www.example.com and your CDN was set up at cache1.example.com, you would point both domains at the same server and then link all your images through the cache1.example.com, while all your text pages and such would pull straight from your webserver. Now, while you would also be able to pull everything including the webpages through the cachers, the issue arises with freshness of the page. This holds especially true when you're working with dynamic PHP content. I ended up running into a bit of an issue. I wanted to maximize the amount of content I'm serving through the CDN, however my website is based off of WordPress. I had two options.. I could rewrite the entire style I'm using to staticly grab the files from the caching server, as opposed to the regular webserver, or I could find a way to dynamically redirect all images to come from the caching server as opposed to the regular webserver. I ended up finding a way to do through the Apache mod_rewrite module. First, I went into the config file for my main toph.ca server and stuck in this line of code: <IfModule mod_rewrite.c> RewriteEngine On RewriteRule ^(.*)(jpeg|jpg|gif|bmp|png|mp3)$ http://cache.toph.ca$0 [NC,L] </IfModule> Then I hopped over and into the config for the caching server (they are running on the same IP using Name-based VirtualHosts) and stuck this in: <files ~ "^(.*)(htm|html|php|js|HTM|HTML|PHP|JS)$"> Order allow,deny Deny from all Satisfy All </files> Now this does two things. First off, this causes all requests to www.toph.ca for media files to be automatically be redirected to cache.toph.ca. It's a simple catch all, and it works! This doesn't entirely reduce the load on the server as the requests still have to hit my Apache server to get the redirect, but my server doesn't actually have to serve the files unless the cacher doesn't have them. The second snippet of code on the cacher prevents the server from serving the actual data html or php files off the server. I don't want that caching server serving web pages to users, or getting them indexed in Google. So there you have it. A quick and dirty way to force all your media content over to a CDN caching service (or any alternative webserver for that matter), and to prevent that server from serving your actual page files.

















