.htaccess redirect to domain

Whether you are using Linux on the desktop or as a server, it's still good that you're using Linux. Linux related questions go here.

Moderator: General Moderators

Post Reply
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

.htaccess redirect to domain

Post by alex.barylski »

I have a web site where you can access it as either 'www' or without...Ideally I would like the .htaccess code required to force a redirect to one or the other -- preferably the 'www' prefix variety.

Cheers,
Alex
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: .htaccess redirect to domain

Post by pickle »

This stuff is all over Google.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Re: .htaccess redirect to domain

Post by alex.barylski »

Would you mind pointing me in the direction of this 'stuff'?

Code: Select all

Force redirect to 'www'
Not sure what the hell I was searching for before but previously the results were dismal...the above popped into my head and voila I have found a few sources:

Code: Select all

RewriteEngine on
RewriteCond %{HTTP_HOST} ^trevorfitzgerald.com [NC]
RewriteRule ^(.*)$ http://www.trevorfitzgerald.com/$1 [L,R=301]
I would like to know whether it's possible to make this a little more portable/dynamic though...can we not substitue the domain for a SERVER variable of the current domain?
thewebhostingdir
Forum Newbie
Posts: 18
Joined: Fri Jul 17, 2009 1:15 am

Re: .htaccess redirect to domain

Post by thewebhostingdir »

This is what I am using for my domain:

RewriteCond %{HTTP_HOST} ^amrita-rao.in$ [OR]
RewriteCond %{HTTP_HOST} ^www.amrita-rao.in$
RewriteRule ^/?$ "http\:\/\/www\.amrita\-rao\.in" [R=301,L]
AccuWebHosting.Com - Windows VPS Hosting
ASP.NET 3.5 | SQL 2005 Database | US Based Hosting Company | 24 X 7 Support | Daily Backups | Uptime Guarantee | Affiliates - $50 Per Sale |
Brick7.com | TheWebHostingDir.com
redmonkey
Forum Regular
Posts: 836
Joined: Thu Dec 18, 2003 3:58 pm

Re: .htaccess redirect to domain

Post by redmonkey »

*If* you have the 'UseCanonicalName' directive set to On then it's a simple case of....

Code: Select all

RewriteCond   %{HTTP_HOST} !^www\.                             [NC]
RewriteRule   .*           http://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]
.. and if you don't the above will get stuck in an endless loop.

This is based on your rule being set in your main (or virtual host) config section, not sure how it would react when used in a directory .htaccess file. It also assumes that your 'ServerName' is set correctly.
Post Reply