.htaccess rewrite are enabled by using the Apache module mod_rewrite, which is one of the most powerful Apache modules and features available. It helps to manipulate the links such that we can transform very long URL’s into short, cute URLs, transform dynamic URL’s like index.php?page=news, news.php?id=10 into SEO friendly and clean format, redirect missing pages, prevent hot-linking, perform automatic language translation, Deny/Allow certain IP/IP Range and many more.
To use this feature mod_rewrite needs to enabled, for e.g. in xampp:
Go to the xampp/Apache/conf/httpd.conf – search for mod_rewrite and you will get the line:
#LoadModule rewrite_module modules/mod_rewrite.so
Remove the # from the line and save it, then restart the Apache.
Now create a file .htaccess in the root directory and include the following,
RewriteRule ^(.*)\.html$ $1.php [NC]
Where, $1 -> first back-reference, NC -> No Case
With this rule any file with .php extension rewrite to .html , e.g. news.php -> news.html
RewriteRule ^([a-zA-Z0-9_]+)\.html$ index.php?page=$1
This rule rewrites URL like index.php?page=contact_us into contact_us.html
Using in PHP code: While using in the php code we must write the href link as contact_us.html instead of
<a href="<?php echo 'www.domain.com/'.'contact_us'.'.html';?>"> Contact Us </a>
RewriteRule ^([a-zA-Z0-9_-]+)$ account.php?id=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ account.php?id=$1
This rule rewrites the URL like http://www.domain.com/account.php?id=54 into http://www.domain.com/54
- If any error occurs with .htaccess file then Internal server error in displayed. The rules can be commented by adding # in front of line.
- No two rules for same back-reference will work, that means a rule defined for single back-reference is enough, so you can have another rule for two back-reference.