Friday, March 25, 2011

url rewriting using .htaccess

URL Rewriting using .htaccess

Here is some example of URL Rewriting. If you are searching for URL Rewriting the bellow code help you for rewriting. In this post we are rewrite URL though .htaccess file. Bellow is some example for URL Rewriting using .htaccess file.

1) Redirecting non www URL to www URL

If we type on browser’s address bar domainname.com it will be redirected to www.domainname.com.

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

2) Rewriting filename.php?id=111 to filename-111.html
Example : profile.php?id=111 to profile-111.html

It’s simple redirection rule in which php extension is hidden from browser address bar and generate dynamic url converted into a static URL.

RewriteEngine on
RewriteRule ^profile-([0-9]+)\.html$ profile.php?id=$1
Note: containing “?” character

3) Rewriting filename.php?id=111 to filename/name/111.html
Example: profile.php?id=111 to profile/kamran/111.html

In the following URL rewriting technique you can display the name of the profile in URL.

RewriteEngine on
RewriteRule ^profile/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ profile.php?id=$2

4) Rewriting http://www.domainname.com/profile.php?username=abc to http://www.domainname.com/abc
Have you seen twitter.com or facebook.com. If you type http://twitter.com/ekamraan or http://facebook.com/ekamran in browser you can see my profile over there. If you want to do same kind of redirection i.e http://domainname.com/profile.php?username=abc to http://domainname.com/xyz then you need to add the following code to the .htaccess file.
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ profile.php?username=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ profile.php?username=$1

5) Redirecting the domainname to a new subfolder of inside www or public_html.

If you have redeveloped your site and all the new development of site in "newfolder” of inside root folder. Then the new development of the site can be access like “http://www.domainname.com/newfolder”. Moving these files to the root newfolder can be a engaged process so you can use bellow code inside the .htaccess file and upload it under the root folder of the site. www.domainname.com point out to the files inside “newfolder”.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^domainname\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.domainname\.com$
RewriteCond %{REQUEST_URI} !^/newfolder/
RewriteRule (.*) /newfolder/$1

No comments: