alias51
alias51

Reputation: 8608

How to rewrite domain.com to www.domain.com

I am trying to edit apache2.conf to rewrite domain.com to www.domain.com:

<IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine On

    # if request is not for a file/directory 
    RewriteCond %{SCRIPT_FILENAME} -d [OR]
    RewriteCond %{SCRIPT_FILENAME} -f
    # then skip from rewrites
    RewriteRule ^ - [L]

    # add www to hostname
    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteCond %{SERVER_ADDR} !=127.0.0.1
    RewriteCond %{SERVER_ADDR} !=::1
    RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

    # forward all the requests to `/index.php
    RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
</IfModule>

I can't see any obvious errors, but the rewrite doesn't work. Any ideas?

Upvotes: 0

Views: 181

Answers (1)

anubhava
anubhava

Reputation: 785038

Minor change in order of your rules:

Options +FollowSymlinks -MultiViews
RewriteEngine On
RewriteBase /

# add www to hostname
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{SERVER_ADDR} !=127.0.0.1
RewriteCond %{SERVER_ADDR} !=::1
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# if request is not for a file/directory 
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
# then skip from rewrites
RewriteRule ^ - [L]

# forward all the requests to `/index.php
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

Upvotes: 1

Related Questions