htaccess rewriterule:根据输入的URL将http重定向到https或https到http(双向)

时间:2012-01-20 18:14:18

标签: http .htaccess mod-rewrite redirect https

任何人都可以帮我写一下rewriterule,根据这些条件重定向http< - > https(返回并强制取决于输入的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之外的所有网址(并保留参数)重定向到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}

1 个答案:

答案 0 :(得分:5)

尝试将以下内容添加到您网站根目录中的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]