I need to force redirect all the pages in Apache to HTTPS except for a few pages. How to write rewrite rule in Apache for this condition?
2 Answers
RewriteEngine On
RewriteCond %{HTTPS} =off
RewriteCond %{REQUEST_URI} !^\/page1\/
RewriteCond %{REQUEST_URI} !^\/page2\/
RewriteRule (.*) https://%{HTTP_HOST}/$1 [L,R=301]
RewriteCond %{HTTPS} =on
RewriteCond %{REQUEST_URI} \/page1\/ [OR]
RewriteCond %{REQUEST_URI} \/page2\/
RewriteRule (.*) http://%{HTTP_HOST}/$1 [L,R=301]
The first rule-set will redirect all pages not accessed via HTTPS, and that are not /page1/
or /page2/
to the same URL but https://
. The second rule-set will make sure that /page1/
and /page2/
are redirected back to http://
if they are accessed via https://
.
-
Something is missing. Don't forget to add the dollar sign '$' if you want match to be exact or else the rule will match as soon as
/page1/
is found anywhere in the URL. that might not be what you want. The page that I was trying to have in http only was/
. it didn't work well without '$'.RewriteCond %{REQUEST_URI} ^\/$
– lano1106Jan 19, 2017 at 21:43 -
1Seems should change to
RewriteRule (.*) https://%{HTTP_HOST}$1 [L,R=301]
, otherwise it will be redirected to example.org/ (double slashes)– SutraSep 5, 2017 at 10:30
A more simple solution:
RedirectMatch ^((?!\/(page1|page2)).*)$ https://%{HTTP_HOST}$1
This will redirect everything except page1 and page2 to https of the current host.
-
For me this is enough but this will not prevent from being able to access the page via https. With this line you make it only accessable with http and https.– rwxMar 8, 2016 at 23:26
-
As far as I understood that was not the original question, maybe your use-case is different?– klodomaMar 9, 2016 at 9:26
-
I had to change to (page1$|page2$) in order to avoid a non-match with page1foo for example: I want /page1 not redirected to https but /page1foo redirected to https Dec 19, 2019 at 13:34