【问题标题】:How to redirect site from www to non-www如何将网站从 www 重定向到非 www
【发布时间】:2020-11-28 18:10:13
【问题描述】:

我有 codeigniter 项目,我有 .htaccess 和以下内容:

RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L,QSA]

现在我想保留这个,因为我不想在地址栏中出现index.php

我有一个域名example.com。现在,当我尝试https://www.example.com 时,它必须重定向到https://example.com

如何使用上面的 .htaccess 文件来做到这一点?

【问题讨论】:

  • 不。不工作。我收到 404 错误。对于这个网址:example.com/abc
  • 抱歉,不清楚您在问什么。 Now I want to keep this index.php as I do not want index.php in addressbar 是什么意思?
  • @AmitVerma 我认为他们的意思是他们想要保留重写规则:RewriteRule ^(.*)$ index.php?/$1 [L,QSA]
  • 是的@Vickel 你是对的。

标签: regex .htaccess mod-rewrite


【解决方案1】:

我建议在您的虚拟主机配置文件中这样做:

从 www 重定向到非 www:

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

主要虚拟主机配置:

<VirtualHost *:80>
    ServerName example.com
    #Server configuration
</VirtualHost>

如果您使用 SSL,那么您应该为您的页面的 SSL 版本配置它,如下所示:

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

Apache 会自动保留 / 之后的任何内容,因此您无需在配置文件中的 / 之后添加任何内容。

如果你想用重写引擎来做,那么这段代码应该适合你:

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

【讨论】:

    【解决方案2】:

    将以下指令放置在您现有规则之前,以将所有内容从 www 重定向到非 www。

    RewriteCond %{HTTP_HOST} ^www\.(.+?)\.?$ [NC]
    RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
    

    %1 反向引用包含主机名,减去 www. 前缀,来自前面的 CondPattern 即。 (.+?) 的值。

    REQUEST_URI 服务器变量包含所请求的相对根(以斜杠开头)URL 路径。

    如果请求 FQDN,这还会删除主机名上的可选尾随点,例如。 www.example.com.。这要求前面的捕获组是非贪婪的,即。 (.+?),而不是简单的 (.+)(它将捕获尾随点)。

    【讨论】:

    • 谢谢它的工作。也感谢你让我正确理解这条规则。我通过这个答案学到了它。再次感谢您:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 2020-12-28
    • 2020-03-15
    • 1970-01-01
    相关资源
    最近更新 更多