Automatically rewriting relative links
This site's RSS feed automatically gets relative HREF and SRC links rewritten to absolute links. Here is how I do it. (Adapting it to other weblogging/CMS software should be pretty simple.)
PHPized RSS feed
Since MovableType doesn't provide any built-in link rewriting capability, I had to write a simple PHP preprocessing layer for it. Since I already had people subscribing to the static filestuff.xml, I had to quietly redirect things over to a dynamic PHP-ified version. So I changed my site's RSS feed location to stuff-rss.php, and put the following into the root .htaccess file:
beesbuzz.biz/.htaccess
RewriteEngine OnRewriteRule stuff.xml /stuff-rss.php [L]
stuff.xml, so be careful.)
URL rewriting filter
Next, I created a globalsitefuncs.php which includes the following:
sitefuncs.php
<? // Rewrite all relative links in a chunk of HTML/XML/etc. to point to the appropriate placefunction rewriteRelative($html, $base) {
} ?>// generate server-only replacement for root-relative URLs
$server = preg_replace('@^([^\:]*)://([^/*]*)(/|$).*@', '\1://\2/', $base);// replace root-relative URLs
$html = preg_replace('@\<([^>]*) (href|src)="/([^"]*)"@i', '<\1 \2="' . $server . '\3"', $html);// replace base-relative URLs (kludgy, but I couldn't get ! to work)
return $html;
$html = preg_replace('@\<([^>]*) (href|src)="(([^\:"])*|([^"]*:[^/"].*))"@i', '<\1 \2="' . $base . '\3"', $html);
Filtered RSS content
Finally, I just needed to filter my entry text (the stuff between<description>...</description>) to use the right URLs. Since MovableType doesn't let you safely encode a chunk of text for both XML CDATA and for a PHP string, I just had to use a here document. Here's what goes inside my description tags in my new RSS template:
echo rewriteRelative(<<<ENTRYBODY_<$MTEntryID$>_XYZZY
<$MTEntryBody encode_xml="1"$>
ENTRYBODY_<$MTEntryID$>_XYZZY
, "<$MTEntryLink encode_php="qq" archive_type="Category"$>");
?></description>
So anyway, that's all there is to it — now URLs are transparently rewritten in a meaningful way.
Caveats
Becausepreg_replace only operates on entire lines at a time, the tag and attribute need to be on the same line; for example,
src="foo">
:/ anywhere in it which doesn't start with /, for whatever that's worth.