首页 > 解决方案 > 需要帮助为 HTTPS 正确配置 .htaccess

问题描述

我正在尝试正确配置和编写我的 .htaccess 文件。有些事情我已经尝试过了,但不知何故,它们都没有奏效。

我正在尝试完成以下重定向:

有些事情可行,但是当进入像 www.domain.com/sub 这样的子目录时,页面会从 HTTPS 更改为 HTTP。

此外,当通过 HTTPS 访问页面时,它不会正确加载 HTML 文件中指定的字体 ()

请参阅下面的代码:

            <IfModule mod_rewrite.c>
            AddType text/x-component .htc
             RewriteEngine On
             RewriteBase /
             RewriteCond %{HTTPS} !=on
             # This checks to make sure the connection is not already HTTPS RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
             # This rule will redirect users from their original location, to the same location but using HTTPS. # i.e. http://www.example.com/foo/ to https://www.example.com/foo/ # The leading slash is made optional so that this will work either in httpd.conf or .htaccess context
             # remove .html; use THE_REQUEST to prevent infinite loops
             RewriteCond %{THE_REQUEST} ^GET\ (.*)\.html\ HTTP
             RewriteRule (.*)\.html$ $1 [R=301]
             # remove index
             RewriteRule (.*)/index$ $1/ [R=301]
             # remove slash if not directory
             RewriteCond %{REQUEST_FILENAME} !-d
             RewriteCond %{REQUEST_URI} /$
             RewriteRule (.*)/ $1 [R=301]
             # add .html to access file, but don't redirect
             RewriteCond %{REQUEST_FILENAME}.html -f
             RewriteCond %{REQUEST_URI} !/$
             RewriteRule (.*) $1\.html [L]
            </IfModule>

标签: .htaccess

解决方案


我想通了,它到目前为止工作:

<IfModule mod_rewrite.c>
AddType text/x-component .htc
 RewriteEngine On
 RewriteBase /
 # Redirect to www 
 RewriteCond %{HTTP_HOST} !^www\.domain\.ch [NC,OR]
 # Redirect to https
 RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"'
 RewriteRule ^ https://www.domain.ch%{REQUEST_URI} [NE,R=301,L]
 # remove .html; use THE_REQUEST to prevent infinite loops
 RewriteCond %{THE_REQUEST} ^GET\ (.*)\.html\ HTTP
 RewriteRule (.*)\.html$ $1 [R=301]
 # remove index
 RewriteRule (.*)/index$ $1/ [R=301]
 # remove slash if not directory
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteCond %{REQUEST_URI} /$
 RewriteRule (.*)/ $1 [R=301]
 # add .html to access file, but don't redirect
 RewriteCond %{REQUEST_FILENAME}.html -f
 RewriteCond %{REQUEST_URI} !/$
 RewriteRule (.*) $1\.html [L]
</IfModule>

推荐阅读