How to rewrite *.example.com to www.example.com

cachesquid

In my network, I've some Ubuntu machines which need to download files from nl.archive.ubuntu.com. Since it's quite a waste of time to download everything multiple times, I've setup a squid proxy for caching the data.

Another use for this proxy was rewriting requests for archive.ubuntu.com or *.archive.ubuntu.com to nl.archive.ubuntu.com because this mirror is faster than the US mirrors.

This has worked quite well, but after a recent install of my caching machine, the configuration was lost. I remember having a separate perl program for handling this rewrite.

How do I setup such a squid proxy which rewrites the host *.example.com to www.example.com and cache the result of the latter?

Best Answer

To rewrite mirror requests from *archive.ubuntu.com to nl.archive.ubuntu.com, you need to create the a rewrite helper and configure squid to use this helper for rewriting requests.

In the squid configuration (e.g. /etc/squid-deb-proxy/squid-deb-proxy.conf), add the line:

url_rewrite_program /etc/squid-deb-proxy/rewrite.pl

As you may have guessed, the helper file needs to be created at /etc/squid-deb-proxy/rewrite.pl, containing:

#!/usr/bin/perl
$mirror = "nl.archive.ubuntu.com";

$| = 1;
while (<>) {
    @line = split;
    $_ = $line[0];
    if (m/^http:\/\/((?:[a-z0-9]+\.)?archive\.ubuntu\.com)\/(.*)/ &&
        $1 ne $mirror) {
        print "http://" . $mirror . "/" . $2 . "\n";
    } else {
        print $_ . "\n";
    }
}

Make it executable (chmod +x /etc/squid-deb-proxy/rewrite.pl), reload the squid configuration and the changes should immediately be visible. You can check this by looking at the speed, or requesting certain files which do only exist on the local mirror (http://nl.archive.ubuntu.com/rsyncscript.txt in my case).