URL Rewriting, SEO friendly URL with htaccess mod_rewrite

Most of the peoples know that why do we using .htaccess file and what is the importance of this .htaccess file for your website, Here in this post you get know about the importance on .htaccess file for your website and some helpful .htaccess tips for your website.

So why we use .htaccess file?

If we are looking to the SEO(Search Engine Optimization) side for your website then .htaccess file is one of the most important factor for your website, lets take an example of URL Rewriting. Why do we need the URL Rewriting for our website? It’s simple; If you noticed the google search results, take a look on the image.

In the above image look on the red circle which shows you the strong part of the URL, and also see on your search term, I think now you understand why do we need URL rewriting, yes because google also see the searched terms into your URL also, so ever provide the clean URL for your website instead of ‘index.php?cat=22&id=255&q=..’ because google can’t understand this URL. Here are some helpful tips to rewrite your website URL, but make sure that before applying the .htaccess file for your website you have to enable the rewrite_module from the apache settings,

Redirect your website permanently to www

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^YourSite.com$
RewriteRule ^(.*)$ http://www.yourSite.com/$1 [R=301]
RewriteCond %{REQUEST_fileNAME} !-d
RewriteCond %{REQUEST_fileNAME} !-f
RewriteRule ^(([^/]+/)*[^./]+)$ /$1.html [R=301,L]


Redirect your website to non-www

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


Please make sure about the ‘RewriteBase’ PATH, if your website is on root directory then just cut and past the code, but if your website is in a folder then you have to set the folder name in the ‘RewriteBase’ like ‘RewriteBase /folder_name/’.

URL rewriting examples:

What you need for URL rewriting is regular expression, of-cause you have to familiar a bit with regular expression because regular expressions play an important role for your URL rewriting, lets take a simple example:

RewriteEngine On

# Returns category/books.html
# OR Returns category/book_shop.html
# OR Returns category/book-shop.html

RewriteRule ^category/([a-zA-Z_-]+)\.html$ category.php?catid=$1


In this simple example take a look after category, the given regular expression allow the only alphabets in small as well as capital format, hyphen(-) and underscore(_). Hope you guys enjoy this post, you are also welcome for any suggestion in the comment section.