+1  A: 

With the following:

$("a[href^='http:']:not([href*='"+window.location.host+"'])").each(function(){
  $(this)
    .attr("href","http://mysite.com?url="+$(this).attr("href"))
    .addClass("external");
});

This HTML:

<a href="http://www.google.com"&gt;Google&lt;/a&gt;
<a href="http://localhost/somepage.html"&gt;Localhost&lt;/a&gt;

Becomes this:

<a class="external" href="http://mysite.com?url=http://www.google.com"&gt;Google&lt;/a&gt;
<a href="http://localhost/somepage.html"&gt;Localhost&lt;/a&gt;
Jonathan Sampson
This is missing some of the possible links.
Justin Johnson
+1  A: 

Try the following, which takes care to escape the URL before appending it to the gateway URL matches more URLs, and is slightly optimized:

var externalLinkPattern = new RegExp("^http://" + window.location.host, "i"),
    gateway             = "http://myurl.com/current/page?url=";

$("a[href^='http:']").each(function() {
    if ( !externalLinkPattern.test(this.href) ) {
        this.href = gateway + escape(this.href);
        $(this).addClass("external");
    }
});
Justin Johnson
+1  A: 

Here's what we use on insightcruises.com, which rewrites all outbound URLs as prefixed with http://insightcruises.com/cgi/go/:

jQuery(function ($) {
        $('a[href^=http:]').each(function () {
                var $this = $(this);
                var href = $this.attr('href');
                href = href.replace(/#/, '%23');
                var newhref = 'http://insightcruises.com/cgi/go/'+href;
                // $('<p />').text(newhref).appendTo('body');                   
                $this.attr('href', newhref);
            });
    });
window.cgigo = function (url, windowName, windowFeatures) {
    if (url.match(/^http:/)) {
        url = url.replace(/\#/, '%23');
        url = 'http://insightcruises.com/cgi/go/'+url;
    };
    window.open(url, windowName, windowFeatures);
};
Randal Schwartz