htaccess redirect to HTTPS except a few urls

2020-02-08 08:16发布

I am new to the htaccess redirect stuff but want to do smth special - and I dont know whats the recommend way and dont know if this is still possible or not.

I have this in my .htaccess file:

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]

Now every URL is redirected to the HTTPS version - this is fine and necessery. But now there are a few exceptions.

For example these urls HAS to be HTTP instead of HTTPS:

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

Is it possible to solve this with the htaccess and when its possible maybe you can send me a reference link or describe how to do this.

Edit

I now have this code:

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]

The goal is that every (!) url gets redirected to HTTPS except ANY url which has commerce_paypal at the beginning.

For example:

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

2条回答
Evening l夕情丶
2楼-- · 2020-02-08 08:48

You can have a RewriteCond to add exceptions in the http->http rule:

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]

Reference: Apache mod_rewrite Introduction

Apache mod_rewrite Technical Details

查看更多
仙女界的扛把子
3楼-- · 2020-02-08 08:49
RewriteCond %{THE_REQUEST} !/commerce_paypal/ [NC]

worked for me. I tried many similar condition rewrites without luck.

查看更多
登录 后发表回答