RewriteEngine to change URLs with Apache and .htaccess – 4 easy and common examples

The RewriteEngine modification of the URL allows for many tricks such as readable URLs and maintaining links after site redevelopment. There are many good reasons to clean up URLs into something readable, including having the customer/client remember the link, being able to identify the content by link alone and hiding the underlying technology. Search engines may also place lower priority on content which appears to be generated dynamically.

1) Consistency

To rewrite every page request to have a “www.” prefix, so 

http://yoursite.com

becomes 

http://www.yoursite.com

 is achieved by:

<div>::CODECOLORER_BLOCK_1::</div>

2) Updating Sites

After redevelopment, containers and directories may change and rewriting is needed to save from breaking old links. To rewrite<code>www.yoursite.com/oldfolder/article1234.php

 to 

www.yoursite.com/NEWfolder/article1234.php

:

<div>::CODECOLORER_BLOCK_2::</div>

3) Make it readable

Guidelines for SEO (Search Engine Optimisation) suggest including the product title in the URL. For example turning <code>products.php?id=12

 to 

products/Rubber-Duck/12.html
<div>::CODECOLORER_BLOCK_3::</div>

4) Fix user typos

<code>www.yoursite.com/products/12

 is not the same as 

www.yoursite.com/products/12/

 (with added slash on the end, but the user won’t care about nerdy details when they only see an error page.

<code>RewriteRule ^products/([0-9][0-9])$ /products/$1/ [R]

Codemonkey of Node.js, Django, PHP and all things HTML5 Solving tech challenges, one bit at a time.

Posted in .htaccess, apache Tagged with: , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*