Best way to redirect example.com to www.example.com

Need help installing PHP, configuring a script, or configuring a server? Then come on in and post your questions! We'll try to help the best we can!

Moderator: General Moderators

Post Reply
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Best way to redirect example.com to www.example.com

Post by Luke »

I've got a site where the secure certificate is set to http://www.example.com and not example.com. How would you recommend redirecting example.com to http://www.example.com so that the browser doesn't whine about a domain mismatch? Redirect directive? mod_rewrite?

EDIT: sorry, the server runs apache - not sure what version
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

Take a look at ServerAlias.
(#10850)
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

I'm on a shared host. I don't think I can use that. :(
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

Even with a virtual host you can usually set the ServerName to http://www.example.com and the ServerAlias to example.com.
(#10850)
Arawn
Forum Commoner
Posts: 42
Joined: Sat May 05, 2007 6:03 am

Post by Arawn »

In Apache 1.3 ServerAlias is only available in Vertual Host and ServerName is available in Virtual Host and Server Config.

Code: Select all

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

# You don't need this but ...
RewriteRule ^$ /index.html [R=301,L]
I still have hosts that are using 1.x versions of Apache.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

A redirect directive is better than mod_rewrite (and arguably a server alias - depending on how it works). With a redirect, the user will be informed of the changed URL, and after the move, the server won't have to run a rewrite on every request.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply