htaccess rewriterule: redirect http to https or ht

2019-05-30 04:36发布

Could anybody please help me to write rewriterule, that redirects http<->https (back and force depending of URL typed) with these conditions:

1) http://www.mydomain.com , http://www.mydomain.com/?p=home , http://www.mydomain.com/?p=home1 , http://www.mydomain.com/?qqq=home are always http, even if https are typed instead of http.

2) all the rest pages are always https, even if http was typed instead of https.

The code below redirects all urls (and keeps parameters), except http://www.mydomain.com , to https.

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

I've tried to add the code below right after the code above to redirect https to http as well (if there are no parametres), so that all pages are always https, except www.mydomain.com, but I had no luck. Also I missed ?p=home, ?p=home1, ?qqq=home - I don't know how to add them.

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

1条回答
Rolldiameter
2楼-- · 2019-05-30 04:43

Try adding the following to your htaccess file in the root directory of your site.

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]
查看更多
登录 后发表回答