htaccess规范名称重定向

时间:2013-04-13 19:19:06

标签: .htaccess rewrite http-redirect

我正在使用SSL证书运营网站。

为了优化我的SEO,我想将所有CNames重定向到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]

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

有人可以帮我解决上面的代码来纠正这个问题吗?

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

以下是.htaccess文件,其中包含以下代码段:

   <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>

2 个答案:

答案 0 :(得分:1)

这是另一种选择:

# 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]

答案 1 :(得分:0)

HTTPS应该“关闭”

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

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

相关问题