URL rewriting using .htaccess – examples
If you are looking for URL rewriting code, following examples will help you.
1] Rewriting category.php?id=12 to category-12.html
It’s a simple redirection in which .php extension is hidden from the browser’s address bar and dynamic url (containing “?” character) is converted into a static URL.
RewriteEngine on RewriteRule ^category-([0-9]+)\.html$ category.php?id=$1
2] Rewriting category.php?id=12 to category/electronics/12.html
SEO expert always suggest to display the main keyword in the URL. In the following URL rewriting technique, you can display the name of the category in URL.
RewriteEngine on RewriteRule ^category/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ category.php?id=$2
3] Redirecting non www URL to www URL (http:// to http://www.)
If user type kapilsakhare.in in browser it will be redirected to www.kapilsakhare.in. Add following code to .htaccess file.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^kapilsakhare\.in$
RewriteRule (.*) http://www.kapilsakhare.in/$1 [R=301,L]
4] Rewriting kapilsakhare.in/articles.php?page=3 to kapilsakhare.in/3
If you want to do the same kind of redirection i.e kapilsakhare.in/3 to http://kapilsakhare.in/articles.php?page=3 then add following code to the .htaccess file.
RewriteEngine On RewriteRule ^([a-zA-Z0-9_-]+)$ articles.php?page=$1 RewriteRule ^([a-zA-Z0-9_-]+)/$ articles.php?page=$1
5] Redirecting domain to subfolder.
Add following code inside the .htaccess file and place it under the root folder of the website. In result, www.subdomain.com point out to the files inside “data” folder.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^subdomain\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.subdomain\.com$
RewriteCond %{REQUEST_URI} !^/data/
RewriteRule (.*) /data/$1