【问题标题】:HTTPS redirect from non www to non wwwHTTPS 从非 www 重定向到非 www
【发布时间】:2020-11-16 15:27:27
【问题描述】:

我有一个非 WWW 域,当我尝试设置重定向到 HTTPS 时,从 http://www.examle.com 重定向到 https://www.example.com 对我有效,但 http://example.com 不适用于 https://example.com。当前的htaccess是:

RewriteEngine On
RewriteCond %{REQUEST_URI} .*index\.html/?$ [NC]
RewriteRule ^(.*)index\.html/?$ https://$1 [R=301,L,NC]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
RewriteCond $1 !index\.php 
RewriteCond $1 !^assets
RewriteCond $1 !^robots.txt
RewriteCond $1 !^sitemap.xml
RewriteRule ^(.*)$ index.php [L]

你能告诉我我做错了什么吗?谢谢

更新:

当前.htaccess

RewriteEngine On 
RewriteCond %{REQUEST_SCHEME} =http 
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC] 
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301] 
RewriteCond %{REQUEST_URI} .*index\.html/?$ [NC] 
RewriteRule ^(.*)index\.html/?$ https://$1 [R=301,L,NC]
RewriteCond $1 !index\.php 
RewriteCond $1 !^assets 
RewriteCond $1 !^robots.txt 
RewriteCond $1 !^sitemap.xml 
RewriteRule ^(.*)$ index.php [L]

【问题讨论】:

    标签: apache .htaccess


    【解决方案1】:

    您正在将此规则用于https 重定向:

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

    第一个条件为%{HTTP_HOST} ^www\.,这意味着它只会匹配以www. 开头的主机名,因此您不会获得http://example.com/ 的重定向。

    您可以改用此重定向规则:

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

    这将执行以下重定向:

    1. http://example.com/ => https://example.com/
    2. http://www.example.com/ => https://www.example.com/

    确保在测试之前清除浏览器缓存。

    【讨论】:

    • 不,还是同样的问题。 :(
    • 此外,将我建议的规则保留为您的 topmost 规则,就在 RewriteEngine 行下方,并清除浏览器缓存。
    • 对不起,我更新了原帖。还是不行。
    • 您的 Apache 版本是多少,我可以知道您的实际域名以进行测试吗?
    • 所以我会问托管公司。非常感谢