Friday, September 3, 2004 at 6:02 pm | Comments off
I've decided that it's time to clean up my URLs. I've really been digging cruft-free URLs lately, as the just look so much better and are much more user friendly than a non cruft-free URL.
What is URL cruft?
Basically, anything that isn't meaningful in the URL is cruft. In my example, I am basically just removing the .php extension from my links. The .php extension is simply telling the web server that the files need to be parsed as PHP and qualifies as cruft. The visitors to this site have no reason to ever see the .php extension, as it's meaningless to them.
How I rewrote the URLs
Since TypeSpace already produces cruft-free URLs for the archived entries, it was simply a matter of rewriting the desired URLs to the corresponding PHP page. It's really very easy to do.
Here's the relevant part of my .htaccess file:
RewriteEngine On RewriteBase / RewriteRule ^about/?$ /about.php RewriteRule ^designer/?$ /designer.php RewriteRule ^archives/?$ /archives.php RewriteRule ^archives/.+ /xblogpro/showblog.php RewriteRule ^sitemap/?$ /sitemap.php RewriteRule ^contact/?$ /contact.php
...and so on for other URLs that I wished to rewrite.
Explaining the rules
First, what we did was turn on the rewrite engine with this command:
RewriteEngine On. That's all there is to that one, either on or off.
Next, we set our rewrite base. For my needs (site wide usage) I set it to a /, which will use my root directory. If I'd only want to apply these rules to a sub-directory such as my software section, I'd set the rewrite base to
/software/. Simple enough, eh?
Finally, we get to the rewrite rules themselves. These are a bit more complicated than what we've seen so far and can be used for far more than what I'm doing with them here.
Those familiar with regex will likely be able to pick up on this quickly, as rewriting is done with a simple set of regular expressions for the rules. Here's how I'm matching:
^ is the start of line anchor, which ensures it starts at the beginning. Next, we match the desired URL, and allow (but don't require) a trailing slash with this bit:
/?$. That optionally (the
? is the 0 or 1 quantifier) matches a trailing slash, while the
$ anchors it to the end. Lastly, we simply add the location of the page that we want to rewrite the URLs to.
Since I needed my archived entries to be sent to /xblogpro/showblog.php, I used this bit of code:
RewriteRule ^archives/.+ /xblogpro/showblog.php. the
.+ matches 1 or more of any character. So, if it finds more characters after the /archives/ part of the URL, people will be sent on to the /xblogpro/showblog.php page, which then fetches the desired entry.
Very simple stuff, but it makes a world of difference. Are you cruft-free?
Comments are automatically closed after 45 days