URL Rewriting Examples Using .htaccess

A common problem if you have a database driven website is you would like to make the urls cleaner and more search engine friendly then try these examples of URL rewriting.

1. Rewriting product.php?id=12 to product-12.html

This is a simple redirection in which the .php extension is hidden from the browser’s address bar and a dynamic url (containing “?” character) is converted into a static URL.

RewriteEngine on
RewriteRule ^product-([0-9]+)\.html$ product.php?id=$1

2. Rewriting product.php?id=12 to product/your-product/12.html

SEO experts always suggest you display the main keyword(s) in the URL. In the following URL rewriting technique you can display the name of the product in URL.

RewriteEngine on
RewriteRule ^product/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ product.php?id=$2

3. Redirecting non www URL to www URL

If you type google.com in your browser it will be redirected to www.google.com. If you want to do same with your website then put the following code in a .htaccess file.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^google\.com$
RewriteRule (.*) http://www.google.com/$1 [R=301,L]

4. Rewriting yoursite.com/user.php?username=xyz to yoursite.com/xyz

If you would like this cleaner and more user friendly URL then you can add the following code to the .htaccess file.

RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ user.php?username=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ user.php?username=$1

5. Redirecting the domain to a new subfolder thats inside public_html.

Lets say you have redeveloped your site and all the new developments reside inside the “new” folder inside of the root folder. Then the new development of the website can be accessed like “example.com/new”. Now moving these files to the root folder can be a hectic process so you can create the following code inside the .htaccess file and place it under the root folder of the website. The result is www.example.com points to the files inside “new” folder.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteCond %{REQUEST_URI} !^/new/
RewriteRule (.*)   /new/$1
  • Share/Bookmark

You can follow any responses to this entry through the RSS 2.0 feed.