我有一个网站,似乎不能从非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重定向到www。
我的Apache配置如下:
RewriteEngine On
### re-direct to www
RewriteCond %{http_host} !^www.example.com [nc]
RewriteRule ^(.*)$ http://www.example.com/$1 [r=301,nc]
我错过了什么?
当前回答
这很简单!
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
其他回答
这是我自己网站的配置,工作起来很有魅力。
<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerAdmin admin@domain.com
ServerName www.domain.com
ServerAlias domain.com
DocumentRoot /var/www/html/domain
<Directory /var/www/html/domain/>
Options FollowSymLinks
AllowOverride All
Require all granted
</Directory>
# Redirect non-www to www
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile /etc/letsencrypt/live/domain.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/domain.com/privkey.pem
</VirtualHost>
</IfModule>
<VirtualHost *:80>
DocumentRoot "what/ever/root/to/source"
ServerName www.example.com
<Directory "what/ever/root/to/source">
Options FollowSymLinks MultiViews Includes ExecCGI
AllowOverride All
Order allow,deny
allow from all
<What Ever Rules You Need.>
</Directory>
</VirtualHost>
<VirtualHost *:80>
ServerName example.com
ServerAlias *.example.com
Redirect permanent / http://www.example.com/
</VirtualHost>
这就是上面代码所发生的情况。第一个虚拟主机块检查请求是否为www.example.com,并在该目录下运行您的网站。
如果做不到这一点,就进入第二个虚拟主机部分。在这里,除www.example.com之外的任何内容都被重定向到www.example.com。
这里的顺序很重要。如果你先添加第二个virtualhost指令,它将导致一个重定向循环。
此解决方案将重定向到您的域www.yourdomain.com的任何请求。
干杯!
这与许多其他建议类似,只是做了一些增强:
不需要硬编码域(适用于接受多个域或环境之间的vhosts) 保留方案(http/https),忽略前面%{REQUEST_URI}规则的影响。 路径部分不受%{REQUEST_URI}等先前rewriterrules的影响。 重写HTTP_HOST} !(数控) RewriteRule ^(.*)$ %{ REQUEST_SCHEME}: / / www. % {HTTP_HOST} / 1美元(R = 301 L)
要将所有直接发送到域名www的请求重定向到301,您可以使用:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^([^.]+\.[^.]+){2,}$ [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
这样做的好处是,如果你有任何有效的子域,这将工作。
example.com重定向到www.example.com
没有重定向
没有重定向
<VirtualHost *:80>
ServerAlias example.com
RedirectMatch permanent ^/(.*) http://www.example.com/$1
</VirtualHost>
这将重定向不仅域名,而且内部 pages.like…… example.com/abcd.html ==> www.example.com/abcd.html example.com/ab/cd.html ? ef = gh ==> www.example.com/ab/cd.html ? ef = gh