【问题标题】:Forcing HTTPS, along with URL rewriting?强制 HTTPS,以及 URL 重写?
【发布时间】:2023-04-02 15:44:01
【问题描述】:

我将这条规则作为我的.htaccess 文件的一部分:

RewriteRule ^view-([0-9]+)$ view.php?id=$1 [L]

这对我来说很好,除了现在我想添加以下功能 - 我想为整个目录实现 HTTPS(这个 .htaccess 在一个名为 /information/ 的目录中),除了这个规则 - 与 view-([0-9]+) 匹配的任何内容。这就是我所拥有的:

RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} ^/information/view-[0-9]+
RewriteRule ^(.*)$ http://www.example.com/information/$1 [R]

RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^/information/view-[0-9]+
RewriteRule ^(.*)$ https://www.example.com/information/$1 [R]

这对我来说基本上工作正常,除了现在当我尝试访问 http://www.example.com/information/view-101 时,它会将我重定向到 https://www.example.com/information/view.php?id=101。如果我尝试访问 https://www.example.com/information/view-101,它也会将我重定向到相同的 URL。

我将这六行代码放在 URL 重写代码的顶部。所有其他 URL 工作正常 - 例如,http://www.example.com/information/about 将带我到 https://www.example.com/information/about,这是正确的功能 - 只是一个 URL 似乎带我到最基本的 URL 形式 - view.php?id=101,忽略所有 URL 重写。

有什么办法可以解决吗?

【问题讨论】:

    标签: php apache .htaccess mod-rewrite url-rewriting


    【解决方案1】:

    从顶部删除这 6 行并编写这样的规则。在您的 .htaccess 文件顶部添加以下行应该对您域的所有 URL 强制执行 HTTPS。它还将您的域的non-www 版本重定向到www 版本:

    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^yourdomain\.com$ [OR]
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://www.yourdomain.com%{REQUEST_URI} [R=301,L]
    

    【讨论】:

    • 我需要对view-[0-9]+ URL 使用 HTTP - 有什么方法可以实现吗?
    【解决方案2】:
    RewriteEngine on
    
    RewriteCond %{HTTPS} on
    RewriteCond %{REQUEST_URI} ^/information/view-[0-9]+
    RewriteRule ^(.*)$ http://%{HTTP_HOST}/information/$1 [L,R]
    
    RewriteCond %{HTTPS} off
    RewriteCond %{REQUEST_URI} !^/information/view-[0-9]+
    RewriteCond %{REQUEST_URI} !^/information/view.php
    RewriteRule ^(.*)$ https://%{HTTP_HOST}/information/$1 [L,R]
    
    RewriteRule ^view-([0-9]+)$ view.php?id=$1 [L]
    

    这可行,但我不明白为什么 apache 使用代码 301 将外部重定向到 view.php。

    【讨论】:

    • 是的,这也是我想知道的。在我的代码中,它重定向到view.php 文件,我不知道为什么。
    猜你喜欢
    • 2012-10-11
    • 2017-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 2015-09-11
    • 1970-01-01
    • 2015-03-13
    相关资源
    最近更新 更多