【问题标题】:RewriteRule for https not workinghttps 的重写规则不起作用
【发布时间】:2017-01-25 20:51:08
【问题描述】:

我试图让我的网站加载 https 版本,无论用户来自哪里或他们输入什么(即:无 example.com)。

我的 htaccess 文件中有以下代码,但如果我只输入 example.com,它不会将站点加载为 https://example.com。我已清除缓存并将 cloudflare 转为开发者模式。

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

之前我也有这行,但它导致了重定向循环。

RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]

有人看到我做错了吗?

RewriteEngine On

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


RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]


ErrorDocument 404 /404custom.php

<ifmodule deflate_module.c>
    DeflateCompressionLevel 1
    DeflateBufferSize 8096
    DeflateMemLevel 8
    DeflateWindowSize 8

    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/xml
</ifmodule>

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/gif A31536000
    ExpiresByType image/jpg A31536000
    ExpiresByType image/jpeg A31536000
    ExpiresByType image/png A31536000
    ExpiresByType image/bmp A31536000
    ExpiresByType image/ico A31536000
    ExpiresByType image/ico A31536000
    ExpiresByType image/icon A31536000
    ExpiresByType image/x-icon A31536000
    ExpiresByType text/css A31536000
    ExpiresByType text/javascript A31536000
    ExpiresByType application/javascript A31536000
    ExpiresByType application/x-javascript A31536000

    # Add a far future Expires header for fonts
    ExpiresByType application/vnd.ms-fontobject A31536000
    ExpiresByType application/x-font-ttf A31536000
    ExpiresByType application/x-font-opentype A31536000
    ExpiresByType application/x-font-woff A31536000
    ExpiresByType image/svg+xml A31536000

    <FilesMatch "\.(js|css|xml|gz)$">
        Header append Vary: Accept-Encoding
    </FilesMatch>

</IfModule>

RedirectPermanent /test_index  https://example.com

【问题讨论】:

  • "^www" 部分 RewriteCond 与您在 https://example.com 的输入不匹配。尝试 https://www .example.com 或修改条件。 (对 SO 的降价有问题)
  • 您还想用https:// 删除www 吗?
  • @anubhava 是的。无论用户输入或不输入www,我都希望它说example.com

标签: apache .htaccess https


【解决方案1】:

您有一个无效的孤立RewriteCond。你还需要一个像这样的OR 子句:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\. [NC,OR]
RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"'
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,NE,L]

清除浏览器缓存后进行测试。

【讨论】:

  • 不幸的是,它不起作用。我清除了浏览器历史记录,按 ctrl + f5,然后转到另一个浏览器。
  • 您更新的答案将 example.com 带到 https 版本,但它会引发错误 example.com 将您重定向太多次。
  • 我清除了缓存并使用了多个其他浏览器进行检查。我刚刚在我的问题中发布了我所有的 htaccess。
  • 这真的很奇怪。每当我取出您的代码时,网站只需输入 example.com 即可转到 https 版本...但是,如果我输入您的代码,则会收到重定向错误。
  • 完美!感谢您提供的所有帮助!
猜你喜欢
  • 2013-07-06
  • 1970-01-01
相关资源
最近更新 更多