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?
Asked
Active
Viewed 1.8k times
2 Answers
29
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://
.

clmarquart
- 4,721
- 1
- 27
- 23
-
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} ^\/$` – lano1106 Jan 19 '17 at 21:43
-
1Seems should change to `RewriteRule (.*) https://%{HTTP_HOST}$1 [L,R=301]`, otherwise it will be redirected to https://example.org// (double slashes) – Sutra Sep 05 '17 at 10:30
9
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.

klodoma
- 4,181
- 1
- 31
- 42
-
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. – rwx Mar 08 '16 at 23:26
-
As far as I understood that was not the original question, maybe your use-case is different? – klodoma Mar 09 '16 at 09: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 – Gilles LAMIRAL Dec 19 '19 at 13:34