我想进行重定向,以便将所有访问http://www.example.com
的用户重定向到http://example.com
。我使用的是DigitalOcean(Ubuntu 14.10 x64)。
首先,我在我的DigitalOcean DNS管理中创建了一个CNAME
记录:
- (Enter name) www
- (Enter hostname) @
其次,我在.htaccess
中放置了以下代码:
Options -Indexes
# Redirect www urls to non-www
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www'.example'.com [NC]
RewriteRule (.*) http://example.com/$1 [R=301,L]
不幸的是,它不起作用。我可以访问http://www.example.com
和http://example.com
,但在访问http://www.example.com
时不会被重定向。
如有任何帮助,我们将不胜感激。
有点偏离主题,但作为替代解决方案,您可以使用PHP;像这样的东西:
if (SUBSTR($_SERVER['HTTP_HOST'], 0, 4) === 'www.') {
header('Location: http'.(ISSET($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' ? 's':'').'://' . SUBSTR($_SERVER['HTTP_HOST'], 4).$_SERVER['REQUEST_URI']);
exit;
}