URL rewriting using .htaccess is pretty common today. Most of the frameworks like WordPress, CodeIgniter,cakePHP etc. provide their own URL rewriting techniques. However, there is always a necessity to beautify the URLs using .htaccess when you are using any of the framework.
Without talking about this more, let’s quickly jump into most commonly used .htaccess URL writing techniques –
1) Rewriting one pair in the URL eg. user.php?id=11 to user/11
RewriteEngine on RewriteRule ^user/([0-9]+)$ user.php?id=$1 |
2) Rewriting with a category or any keyword in the URL eg. user.php?id=11&name=joe to user/joe/11
It is always a good idea to keep the relevant keyword in the URL. It makes URL more relevant and also helps in the SEO of the web pages. In this example keeping the name Joe in the URL will help recognize that it’s going to be Joe’s profile page and in SEO keyword Joe will be counted, since this page is going to be about Joe.
RewriteEngine on RewriteRule ^user/([a-zA-Z]+)/([0-9]+)$ user.php?id=$2 |
3) Always suffix trailing / eg. redirect tools/twitter to tools/twitter/
The following example will automatically redirect you from http://www.digimantra.com/tools/twitter to http://www.digimantra.com/tools/twitter/ (notice the trailing slash(/)). The 301 redirect helps you avoid the duplicate content and saving the SEO juice from the search engine. If the URL is accessible with and without the trailing slash (/), search engine will treat these as two different webpages and hence lesser SEO benefit. Using the following rule you can avoid this.
RewriteRule ^tools\/twitter$ tools/twitter/ [L,R=301] |
4) Replace all .php with .html eg. profile.php to profile.html
Options +FollowSymlinks RewriteEngine on RewriteRule ^(.*)\.html$ $1.php [NC] |
In the above example [NC] means not case sensitive,meaning PROFILE.php and profile.php both will be redirected to profile.html
5) Redirect domain.com to www.domain.com , again for the SEO purpose (canonical URL)
I have a complete post showing how to Prefix www to your domain using htaccess , sharing the same code snippet from there.
RewriteEngine On RewriteEngine On RewriteCond %{HTTP_HOST} ^domain.com [NC] RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,L] |
Hope the above .htaccess rules help you in some way.
Stay Digified!!
Sachin Khosla