我有一个网站,似乎不能从非www重定向到www。

我的Apache配置如下:

RewriteEngine On
### re-direct to www
RewriteCond %{http_host} !^www.example.com [nc]
RewriteRule ^(.*)$ http://www.example.com/$1 [r=301,nc] 

我错过了什么?


当前回答

如果你只想加载www的https版本,在apache虚拟主机文件中使用下面的配置。所有这些都可以放在一个文件中。

重定向所有HTTP到www的HTTPS:

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

重定向HTTPS非www到HTTPS www:

<VirtualHost *:443>
    ServerName example.com
    Redirect permanent / https://www.example.com/
</VirtualHost>

实服务器配置

<VirtualHost *:443>
    ServerAdmin hostmaster@example.com
    DocumentRoot "/path/to/your/sites/.htaccess-file-folder"
    SetEnv APPLICATION_ENV "production"

    <Directory "/path/to/your/sites/.htaccess-file-folder">
            Options Indexes FollowSymLinks
            DirectoryIndex index.php index.html
            AllowOverride All
            Order allow,deny
            Allow from all
    </Directory>
    ServerName www.example.com
    
    SSLEngine ON
    SSLCertificateFile "/path/to/your/example.cert.pem"
    SSLCertificateKeyFile "/path/to/your/example.key.pem"

    ErrorLog /path/to/your/example.com-error.log
    CustomLog /path/to/your/example.com-access.log combined
    #Your other configurations if you have
</VirtualHost>

其他回答

<VirtualHost *:80>
    ServerAlias example.com
    RedirectMatch permanent ^/(.*) http://www.example.com/$1
</VirtualHost>

我发现在使用多个vhost时使用ServerAlias更容易(也更有用)。

<VirtualHost x.x.x.x:80>
    ServerName www.example.com
    ServerAlias example.com
    ....
</VirtualHost>

这也适用于https vhosts。

我使用的代码是:

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

我运行了这个…

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

我需要这是通用的25+域在我们的新服务器,所以这个指令是在我的virtual.conf文件在<Directory>标签。(dir是所有docroots的父目录)

不过,我不得不对重写规则做一些修改,因为完整的docroot正在进行模式匹配,尽管http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html说它只是主机和端口之后的东西。

重定向域。TLD到www。

以下行可以添加到Apache指令或.htaccess文件中:

RewriteEngine on    
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

其他的子域仍在工作。 不需要调整线条。只需复制/粘贴到正确的位置。

如果你修改了vhost,不要忘记应用apache的变化。

(基于默认的Drupal7 .htaccess,但应该在很多情况下工作)