Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I want to rewrite urls to the www subdomain if the user omits it, i.e. example.com/something.html to www.example.com/something.html

The config below doesn't work, user remains on example.com. There's probably missing something very simple...

<VirtualHost *:80>

    DocumentRoot /data/domains/example.com/www/public
    ServerName www.example.com
    ServerAlias example.com
#        ErrorDocument 404 /index.pl page_not_found
#          CustomLog /logs/apache/example.com/access_log combined
#        RedirectMatch 301 ^(.*)$ http://www.example.com/

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

share|improve this question

migrated from superuser.com Dec 9 '10 at 4:12

This question came from our site for computer enthusiasts and power users.

marked as duplicate by MadHatter, HBruijn, Ward, mdpc, voretaq7 yesterday

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

add comment

3 Answers

up vote 3 down vote accepted

My own solution to this is to use two virtual hosts, one with the non-www that redirects to the other one with the www as follows:

<VirtualHost *:80>
     ServerName example.com
     Redirect permanent / http://www.example.com/
</VirtualHost>

<VirtualHost *:80>
     DocumentRoot /data/domains/example.com/www/public
     ServerName www.example.com
</VirtualHost>

That way, I don't have to mess-up with the cryptic .htaccess rules as much as possible. KISS principle, remember ;)

Ismael Casimpan

share|improve this answer
add comment

I do thing in the different way ;) This is my working rules:

# redirect www.fclose.com/* to fclose.com/*
RewriteBase   /
RewriteCond   %{HTTP_HOST}             ^www\.fclose\.com$
RewriteRule   ^(.*)                    http://fclose.com/$1 [R=301,L]

You may try these rules:

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

I change the one above and get them.

share|improve this answer
add comment

Change your RewriteRule to:

RewriteCond %{HTTP_HOST} ^domain\.com

So the whole thing should look like:

<IfModule mod_rewrite.c>
    RewriteEngine on 
    RewriteCond %{HTTP_HOST} ^domain\.com
    RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
</IfModule>
share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.