Pages

20 Jan 2013

Apache #2: Pretty URLs and .htaccess mod_rewrite

How do I get Pretty URLs?

Ever seen professional sites with tidy urls, like www.example.com/products/small-dinosaur? Well, this is likely due to an Apache rewrite, which 'prettifies' the url - the underlying url is probably something like: www.example.com/products.php?id=small-dinosaur

What are .htaccess Files?

You should avoid using .htaccess files completely if you have access to httpd main server config file.[from the official Apache site]
If you have access to the httpd.conf file in Apache's conf directory (well, it's there in the XAMPP version, yours may be elsewhere), you can do your stuff there. However, many people get a bit twitchy with changing the main config file - if you're prone to a bit of twitchiness, make a backup copy first. If you're looking for this file on your shared hosting site, then you'll probably be disappointed.
Anyway... so what's the problem with .htaccess? Well nothing really, it's just a little bit slower than httpd.
In order to create a .htaccess file, you just need a text editor - remember to save it with a blank filename and the htaccess extension. Alternatively, save as htaccess.txt and then rename the file.
Hold on... I haven't mentioned what these .htaccess files are yet, have I? OK, the good people of Wikipedia have an entry, but in general, .htaccess files are used to:
  • rewrite urls
  • serve error responses, like 404 or 301
  • authenticate or block users
  • control caching
We'll just be looking at the first use in this post. Let's kick off and have a look at a few examples. BTW - there are some really nice rewrite generators out there - my favourite at the moment is GenerateIt.

Examples

Say we want to convert:

http://www.example.com/product.php?id=7&name=teddy_bear into:

http://www.example.com/products/7/teddy_bear

We'd need the following code in the .htaccess file:

Options +FollowSymlinks
RewriteEngine On
RewriteRule ^products/([^/]*)/([^/]*)$ /product.php?id=$1&name=$2 [L]

Here's another:

http://www.example.com/index.php?page=toys&category=dolls into:

http://www.example.com/toys/dolls/

Here's the code:

Options +FollowSymlinks
RewriteEngine On
RewriteRule ^([^/]*)/([^/]*)/$ /index.php?page=$1&category=$2 [L]

Where do I put the File?

.htaccess files are active in the directory into which they're placed and all underlying subdirectories, so if you have site-wide directives, you can place the file in your public root.

Further Resources


1 comment: