htaccess重定向到HTTPS,除了几个网址

时间:2014-10-17 14:08:52

标签: regex apache .htaccess mod-rewrite redirect

我是htaccess重定向的新手,但是想要做特殊的smth - 我不知道推荐的方式是什么,不知道这是否仍然存在。

我在.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版本 - 这很好并且必要。但现在有一些例外。

例如,这些网址必须是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]

目标是每个(!)网址都会被重定向到HTTPS,除了任何在开头都有commerce_paypal的网址。

例如:

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

2 个答案:

答案 0 :(得分:19)

您可以RewriteCondhttp->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

答案 1 :(得分:0)

RewriteCond %{THE_REQUEST} !/commerce_paypal/ [NC]

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

相关问题