【问题标题】:htaccess Canonical names redirect [closed]htaccess 规范名称重定向 [关闭]
【发布时间】:2013-04-06 04:36:15
【问题描述】:

我正在使用 SSL 证书运行一个网站。

为了优化我的 SEO,我想将所有 CName 重定向到 https://example.com

同一地址有 4 种变体: https://example.com https://www.example.com http://example.com http://www.example.com

这段代码几乎可以工作:

RewriteCond %{HTTP_HOST} ^www\.example\.com$ [OR]
RewriteCond %{HTTPS} =on
RewriteRule ^.*$ https://example.com/$0 [R,L]

但是,其中一个 URL 不会重定向。如果我只输入 example.com (http://example.com),则 URL 不会重定向到 https://example.com

谁能帮我用上面的代码纠正这个问题?

回应下面乔恩的回答。我将代码的 sn-p 添加到现有的 .htaccess 文件中。由于我不熟悉 .htaccess,我想知道该 sn-p 周围的代码是否导致了重定向循环?

这是 .htaccess 文件,包括下面的 sn-p:

   <IfModule mod_rewrite.c>
    RewriteEngine On

    # Installation directory
    RewriteBase /

    # Protect application and system files from being viewed
    RewriteRule ^(application|modules|system|tests|sql) - [F,L]

    # Allow any files or directories that exist to be displayed directly
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    # Rewrite all other URLs to index.php/URL
    RewriteRule .* index.php?kohana_uri=$0 [L,QSA]

    #redirect CNames to non www
    RewriteCond %{HTTP_HOST} ^www\.example\.com$ [OR]
    RewriteCond %{HTTPS} off
    RewriteRule ^.*$ https://example.com/$0 [R,L]

   </IfModule>

【问题讨论】:

标签: .htaccess rewrite http-redirect


【解决方案1】:

HTTPS 应该“关闭”

RewriteCond %{HTTP_HOST} ^www\.example\.com$ [OR]
RewriteCond %{HTTPS} off
RewriteRule ^.*$ https://example.com/$0 [R,L]

因为您希望主机以 www 开头或关闭 HTTPS。

【讨论】:

  • 感谢您的回答,但是当我添加它并导航到他的站点时,我收到一个错误,提示存在“重定向循环”?
  • @DougFirr 不知道为什么你会收到太多重定向,这些规则对我来说很好用。不过,查看您的 htaccess 文件,您可能希望将这些规则放在 其余规则之前。
  • 再次感谢您的反馈。尝试将 sn-p 移动到 .htaccess 文件的开头,但结果相同 :-( 我想知道这是否是 CMS 配置的结果。我知道在他的配置文件中有一行代码可以使用 https 或 http,这意味着要在后端进行管理。嗯,可以尝试将其关闭并查看其作用
  • 因此尝试在后端关闭 https 以仅依赖 .htaccess 文件。结果相同。同样感谢乔恩,我很感激
【解决方案2】:

这是另一种选择:

# http www and non-www to https non-www
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} (?:www\.)?(.*)  [NC]
RewriteRule ^(.*) https://%1/$1          [R=301,L]

# https www to non-www
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST}  ^www\.(.*) [NC]
RewriteRule ^(.*) https://%1/$1      [R=301,L]

我猜这段代码的最佳位置是在RewriteBase / 指令下方。

如果有循环,那么前面的代码几乎不会产生循环。也许通过第二条规则,您可以尝试添加一个条件,如下所示:

# Add next line before the rule
RewriteCond %{REQUEST_URI}  !index\.php   [NC]
# Current rule
RewriteRule .* index.php?kohana_uri=$0 [L,QSA]

【讨论】:

  • 感谢您的反馈,但反馈循环仍然存在。不过,我确实摆弄了一下,并认为我可以正常工作。我将就此发布一个新问题。再次感谢
猜你喜欢
  • 2012-12-03
  • 1970-01-01
  • 2010-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多