如何将domain.com重写为www.domain.com

时间:2014-02-01 15:02:20

标签: apache .htaccess mod-rewrite

我正在尝试编辑apache2.conf以将domain.com重写为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>

我看不到任何明显的错误,但重写不起作用。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

按照规则进行细微更改:

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]