将用户从www重定向到非www URL


Redirect users from www to non www URL

我想进行重定向,以便将所有访问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.comhttp://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;
}