【问题标题】:htaccess redirect to HTTPS except a few urlshtaccess 重定向到 HTTPS,除了几个 url
【发布时间】:2014-12-13 03:32:42
【问题描述】:

我是 htaccess 重定向的新手,但想做一些特别的事情 - 我不知道推荐的方法是什么,也不知道这是否仍然可行。

我的 .htaccess 文件中有这个:

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

现在每个 URL 都被重定向到 HTTPS 版本 - 这很好,也很有必要。但现在有一些例外。

例如,这些 url 必须是 HTTP 而不是 HTTPS:

http://www.mywebsite.com/another/url/which/has/to/be/http
http://www.mywebsite.com/and_again?var=a

是否可以使用 htaccess 解决此问题,如果可能,您可以向我发送参考链接或描述如何执行此操作。

编辑

我现在有这个代码:

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTPS} off 
RewriteCond %{THE_REQUEST} !\s/+(/commerce_paypal/*)\s [NC] 
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

目标是 每个 (!) url 都被重定向到 HTTPS,但开头有 commerce_paypal 的任何 url 除外。

例如:

mydomain.com/commerce_paypal  <- http
mydomain.com/commerce_paypal/smth/else <- http
mydomain.com/what/ever <- https

【问题讨论】:

    标签: regex apache .htaccess mod-rewrite redirect


    【解决方案1】:

    您可以使用RewriteCondhttp-&gt;http 规则中添加例外:

    RewriteEngine On
    
    RewriteCond %{HTTP_HOST} !^www\.
    RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
    # force https:// for all except some selected URLs    
    RewriteCond %{HTTPS} off
    RewriteCond %{THE_REQUEST} !/commerce_paypal/ [NC]
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
    # force http:// for selected URLs
    RewriteCond %{HTTPS} on
    RewriteCond %{THE_REQUEST} /commerce_paypal/ [NC]
    RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    

    参考:Apache mod_rewrite Introduction

    Apache mod_rewrite Technical Details

    【讨论】:

    • 感谢您的回答。我现在有这个 sn-p 来强制例外: RewriteCond %{HTTPS} off RewriteCond %{THE_REQUEST} !\s/+(/commerce_paypal/*)\s [NC] RewriteRule ^ https://%{HTTP_HOST}% {REQUEST_URI} [L,R=301] 如您所见,计划是强制 commerce_paypal 不再是 HTTPS。有一些 commerce_paypal URL,所以我输入了“commerce_paypal/*”,这样 / 之后的每个 url 部分都是可能的,但必须是 HTTP。但这不起作用......有什么想法吗?
    • 您可以在问题中发布代码以使其可读,而不是 cmets。
    • 嗯,您的正则表达式不正确。用更正的版本查看我的更新答案。
    • 非常感谢!这帮助了我 :) 太好了!
    • @anubhava,您的解决方案在本地为我工作,但我的暂存环境位于负载均衡器后面,陷入无限重定向循环。我添加了RewriteCond %{HTTP:X-Forwarded-Proto} !https 来捕获除我排除的一个 URL 之外的所有 URL,并将其发送到 HTTPS。然后在将我的一个 URL 重定向到 HTTP 的第二个块中,我根据此处的建议添加了 RewriteCond %{HTTP:X-Forwarded-Proto} =httpsdocs.acquia.com/article/…
    【解决方案2】:
    RewriteCond %{THE_REQUEST} !/commerce_paypal/ [NC]
    

    为我工作。我尝试了许多类似的条件重写,但没有运气。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-30
      • 2014-11-27
      • 2019-09-15
      • 1970-01-01
      相关资源
      最近更新 更多