【问题标题】:htaccess rewriterule: redirect http to https or https to http (both ways) depending on URL typedhtaccess rewriterule:根据输入的 URL 将 http 重定向到 https 或 https 到 http(两种方式)
【发布时间】:2012-01-20 18:14:17
【问题描述】:

谁能帮我写重写器,在这些条件下重定向 httphttps(返回和强制取决于输入的 URL):

1) http://www.mydomain.com , http://www.mydomain.com/?p=home , http://www.mydomain.com/?p=home1 , http://www.mydomain.com/?qqq=home 始终是 http,即使键入的是 https 而不是 http。

2) 所有其余页面始终为 https,即使输入的是 http 而不是 https。

下面的代码将除http://www.mydomain.com 之外的所有url(并保留参数)重定向到https。

#redirects http to https if there are parameters
RewriteCond %{HTTPS} off
RewriteCond %{QUERY_STRING} !^$
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

我尝试在上面的代码之后添加下面的代码以将 https 也重定向到 http(如果没有参数),以便所有页面始终为 https,除了 www.mydomain.com,但我有没运气。我也错过了 ?p=home, ?p=home1, ?qqq=home - 我不知道如何添加它们。

RewriteCond %{HTTP} off
RewriteCond %{QUERY_STRING} ^$
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}

【问题讨论】:

    标签: http .htaccess mod-rewrite redirect https


    【解决方案1】:

    尝试将以下内容添加到站点根目录中的 htaccess 文件中。

    RewriteEngine on
    RewriteBase /
    
    #determine if page is supposed to be http
    #if it has p=home or p=home1 or qqq=home in querystring
    RewriteCond %{QUERY_STRING} (^|&)(p=home1?|qqq=home)(&|$) [NC,OR]
    #or if query string is empty
    RewriteCond %{QUERY_STRING} ^$
    #set env var to 1
    RewriteRule ^ - [E=IS_HTTP:1]
    
    
    #all pages that are supposed to be http redirected if https
    RewriteCond %{HTTPS} on
    RewriteCond %{ENV:IS_HTTP} 1
    RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [R,L=301]
    
    #all other pages are sent to https if not already so
    RewriteCond %{HTTPS} off
    RewriteCond %{ENV:IS_HTTP} !1
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R,L=301]
    

    【讨论】:

    • 哇... 似乎我理解了原理,但我永远不会从头开始自己编写它。人们如何在不到一年的时间内回答我的问题?..:) 另一个问题是:您能解释一下“home1”吗?这是否意味着最后一个符号(“1”)无效的“home1”或“home1”?谢谢你。第二个问题:[E=IS_HTTP:1] 还是 [ENV=IS_HTTP:1]?谢谢。
    • @Haradzieniec home1? 匹配 home 或 home1 即 ? 使 1 可选。 E 或 env 将起作用。
    • 非常感谢。它有效,但是....我不知道这是否是该主题的问题,而不是另一个问题...使用您的代码,https 是红色的,并且在 Chrome 中被划掉,而在 FF 中也会发生类似的错误。删除您的代码后,一切正常,SSL 证书显示正常 - 它是绿色的。它甚至适用于您的代码的第一个和第三个块(但没有第二个块,它以“RewriteCond %{HTTPS} on”开头)。可能是什么原因?非常感谢。
    • Chrome中交叉https的问题在这里:图片在文件夹中。关于 Ulrich Palha 建议的 rewritecond(他是对的),文件夹中的图片将始终通过 http 加载。这就是https页面有错误的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    相关资源
    最近更新 更多