【问题标题】:.htaccess redirect HTTP to HTTPS with mod_rewrite not working.htaccess 将 HTTP 重定向到 HTTPS,但 mod_rewrite 不起作用
【发布时间】:2018-02-14 11:26:01
【问题描述】:

我正在尝试使用 htaccess 和 mod_rewrite 将我网站的所有连接从 http 重定向到 https,我已经尝试了所有可能的方法但仍然无法正常工作,我收到如下错误:页面未正确重定向

htaccess 代码如下:

ErrorDocument 404 http://www.example.com/error.php

<IfModule mod_rewrite.c>

Options -Indexes

Options +FollowSymlinks

RewriteEngine on

RewriteBase /

RewriteCond %{HTTPS} on 

RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteCond %{HTTP_HOST} !^www\. [NC]

RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

RewriteRule ^([^/]*)\.html$ /index.php?lang=$1 [L]

RewriteRule ^sites/examplesite/([^/]*)\.html$ /index.php?lang=$1 [L]

RewriteRule ^([^/]*)/examplesite/([^/]*)\.html$ /index.php?lang=$1&page=$2 [L]

RewriteRule ^([^/]*)/([^/]*)\.html$ /index.php?lang=$1&page=$2 [L]

RewriteRule ^([^/]*)/([^/]*)/([^/]*)\.html$ /index.php?lang=$1&idCat=$2&page=$3 [L]

RewriteRule ^([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)\.html$ /index.php?lang=$1&cat=$2&filter=$3&pa=$4&page=$5 [L]

RewriteRule ^sites/examplesite/([^/]*)/([^/]*)\.html$ /index.php?lang=$1&page=$2 [L]

RewriteRule ^([^/]*)/([^/]*)/([^/]*)\.html$ /index.php?lang=$1&show=$2&page=$3 [L]

RewriteRule ^sites/examplesite/([^/]*)/([^/]*)/([^/]*)/([^/]*)\.html$ /index.php?lang=$1&itemID=$2&idCat=$3&page=$4 [L]

RewriteRule ^sites/examplesite/([^/]*)//([^/]*)/([^/]*)\.html$ /index.php?lang=$1&idCat=$2&page=$3 [L]

RewriteRule ^([^/]*)/([^/]*)/([^/]*)/([^/]*)\.html$ /index.php?lang=$1&idCat=$2&client_id=$3&page=$4 [L]

</IfModule>

<FilesMatch "\.(ttf|otf|eot|woff)$">
  <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
  </IfModule>
</FilesMatch>



   php_flag display_errors On

【问题讨论】:

    标签: .htaccess http redirect mod-rewrite https


    【解决方案1】:

    关于您的主要问题,从您的代码来看,这部分 i 是您认为会强制所有 http 请求到 https:

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

    很明显,您还想为无 www 添加 www ,所以首先,当您想捕获无 https 请求时,您应该像这样写:

    RewriteCond %{HTTPS} off 
    

    因为它的条件类似于说,如果请求不是进入 https,而是在您的代码中,您只能自己捕获 https 请求并再次强制它们。

    用下面的代码代替上面的代码:

     RewriteCond %{HTTPS} off [OR]
     RewriteCond %{HTTP_HOST} !^www\. [NC]
     RewriteRule ^(.*)$ https://www.yourwebsite.com/$1 [R=302,L]
    

    测试它,如果可以,将302 更改为301 以获得永久重定向

    【讨论】:

    • 还是不行,同样的错误,页面没有正确重定向……链接改成https但是看不到页面内容。prnt.sc/iezy6j
    最近更新 更多