Posts Tagged ‘htaccess’

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/

how to add www to your domain name using .htaccess file

Thursday, June 19th, 2008

If you are wanting to add www. to your domain name automatically such as changing http://yourdomain.com to http://www.yourdomain.com then you can use a few simple lines in your .htaccess file in your public_html folder. This is especially useful for SEO as search engines index the domain with and without the www. as seperate sites.

Note that you will need the mod rewrite plugin active in your apache configuration in order to do this

#Turn on rewriting engine
RewriteEngine on
# If HTTP_HOST starts with yourdomain.com
# (Note: In a regular expression you have to escape the .
# with the backslash)
RewriteCond %{HTTP_HOST} ^yourdomain\.com$
# change the URL to the URL with www prepended and
# use a permanent redirect
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [R=301,L]

################################################
# ALL LINES STARTING WITH A # ARE COMMENTS,    #
# AND SHOULD BE REMOVED IN YOUR VERSION        #
#                                              #
# LEAVING THEM IN BETWEEN THE RewriteCond and  #
# RewriteRule LINE WILL CAUSE THE FILE TO      #
# FUNCTION INCORRECTLY                         #
################################################

.htaccess file generator

Enter your domain name below without the www like yourdomain.com and click submit to generate your htaccess file