Posts Tagged ‘mod_rewrite’

How to enable mod_rewrite in Apache

Sunday, June 22nd, 2008

To enable the rewrite module in Apache you will need access to the httpd.conf file, located in {Apache folder}/conf/httpd.conf
Open up the file, and search for
#LoadModule rewrite_module modules/mod_rewrite.so
and simply remove the # from the start of the line. Then save the file, and restart the Apache server. You should now be able to use the mod_rewrite functionality on your server. to test this, create a new file called test.php in your root html folder, with the following code in it

and put

RewriteEngine On
RewriteBase /
RewriteRule ^test/(.+)$ test.php?p=$1 [L]

into a .htaccess file in the same folder

Don’t forget to delete these two files after testing

Making dynamic/pretty URL’s for PHP scripts

Friday, June 20th, 2008

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/