Andrew Fiebert, DBA and Developer
The blogfolio of
developer Andrew Fiebert

Posts Tagged ‘Apache’

htaccess, mod_rewrite and url reformatting

(in Web Development on Friday, November 23rd, 2007 by Andrew)

So you are a web developer and the search engines just aren’t picking up your deep links. Maybe your links aren’t that deep but you want to provide more memorable URLs. Either way the solution lines in .htaccess file and mod_rewrite. Once I tried to do URL reformatting within PHP and not only was it ugly and hacky, it really didn’t work. Plus http://fiebert.com/index.php/experience just doesn’t look as sweet as http://fiebert.com/portfolio/experience.

This whole revamping of your URL structure is actually fairly easy. The first step is creating a file “.htaccess” in your root folder. From there we just decide exactly how you want to structure your URLs. This is the first part of my file:

#These two lines are always included
Options +FollowSymlinks
RewriteEngine on#If any url has the www in it, we remove it to show http://fiebert.com
RewriteCond %{http_host} ^www\.fiebert\.com [nc]
RewriteRule ^(.*)$ http://fiebert.com/$1 [r=301,nc]

Now to start replacing URLs like http://fiebert.com/college.php?project=perl with http://fiebert.com/portfolio/college/perl gets a little more complex. The htaccess file uses some basic regular expression (regexp) syntax, this is from the htaccess docs

Text:
.           Any single character
[chars]     Character class: One  of chars
[^chars]    Character class: None of chars
text1|text2 Alternative: text1 or text2 (ie. "or")

Quantifiers:
?           0 or 1 of the preceding text
*           0 or N of the preceding text	(hungry)
+           1 or N of the preceding text

Grouping:
(text)	Grouping of text
	(either to set the borders of an alternative or
	for making backreferences where the nth group can
	be used on the target of a RewriteRule with $n)

Anchors:
^           Start of line anchor
$           End   of line anchor

Escaping:
\char		escape that particular char
		(for instance to specify special characters.. ".[]()" etc.)

Keeping that in mind, below is how I replace http://fiebert.com/college.php?project=perl with http://fiebert.com/portfolio/college/perl

#Change http://fiebert.com/college.php?project=perl to http://fiebert.com/portfolio/codedrink/perl
RewriteRule ^portfolio/(.+)/(.+) $1.php?project=$2 [nc]
RewriteRule ^portfolio/(.+) $1.php [nc]