Making dynamic/pretty URL’s for PHP scripts

We’ve all seen sites where the URL looks really ugly, i.e.
example.com/product.php?id=12345&action=purchase&num=2

However, over the last few years, more and more sites have converted to dynamic/pretty URL’s, where it looks more like example.com/buy/12345/2/

Using some simple regular expressions and the rewrite module of apache you can create pretty page URL’s

So we have three sections, clearly coloured below:
example.com/buy/12345/2/ need to map to
example.com/product.php?id=12345&action=purchase&num=2

Here’s the RewriteRule for this example, which should be put inside your .htaccess file

RewriteRule ^buy/(\d+)/(\d\d?)/?$ /path/to/public_html/product.php?id=$1&action=purchase&num=$2 [L]

This is a case sensitive search, ie, /BUY/ would not work. If you wish to make it case insensitive, change the [L] to [L,NC]
Note: If you haven’t already got

RewriteEngine on
RewriteBase /

in the top of your .htaccess file, you will need to add it. The first line is required to get the rewrite engine working, and the second is to start matching the URL after the / on the end of example.com/

Tags: , , , , ,

Leave a Reply

You must be logged in to post a comment.