Skip to main content

Simple URL rewrite to www domain

If your domain can be reached trough domain.com and www.domain.com and you don’t want that, you can do simple rewrite with .htaccess file to change this.

1. Create new file with you favorite text editor and save it as: .htaccess
2. Copy/paste these lines in your file:

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

3. Replace “domain” with your domain name

For example, rewrite for my domain (http://www.bobz.com.hr) would be:

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

4. Save file and upload it to your web site root directory (public_html)

Also you can revers this, if you want to display your domain as: http://domain.com, then you would use this:

RewriteEngine on
RewriteCond %{http_host} ^www.bobz.com.hr$
RewriteRule ^(.*)$ http://bobz.com.hr/$1 [R=301,L]

I think all of modern CMS systems have url rewrite by default included, so you can use built in functions. This example is useful if you are working on a static HTML site.
Be sure that you are using Apache web server and have enabled mod_rewrite module before using these rules.

Leave a Reply

Your email address will not be published.

Please don’t paste any HTML, Js or PHP code into comments box, use pastebin.com or similar service to share code examples.

Characters left: 1000