user548958
user548958

Reputation: 35

mod_rewrite: 2 files should always be SSL, the rest always HTTP

I want to ensure that a small number of URLs in my application are always served over SSL; the rest should always be served over HTTP.

My current mod_rewrite ruleset goes like this:

RewriteCond %{HTTPS}            off
RewriteRule ^/?account.html$    https://example.com/account.html [L]
RewriteRule ^/?checkout.html$   https://example.com/checkout.html [L]

RewriteCond %{HTTPS}            on
RewriteCond %{REQUEST_URI}      !/account.html$
RewriteCond %{REQUEST_URI}      !/checkout.html$
RewriteRule (.*)                http://example.com/$1 [L]

The first file in each RewriteCond works OK (account.html in this example). The 2nd file doesn't work - the server is "redirecting in a way that will never complete".

Any ideas on how to make this work? In production there'll be more than 2 SSL-only URLs, likely 7 - 10.

Thanks

Upvotes: 1

Views: 36

Answers (1)

Justin Iurman
Justin Iurman

Reputation: 19016

You must use R flag to redirect url

RewriteEngine On

# redirect account.html or checkout.html (if http) to https
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} ^/(account|checkout)\.html$ [NC]
RewriteRule ^ https://%{HTTP_HOST}/%1.html [R,L]

# redirect other urls (if https) to http
RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} !^/(account|checkout)\.html$
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [R,L]

Note: i used R flag, which performs a 302 redirect by default. Feel free to replace [R,L] by [R=301,L] when it works (301 redirect is a permanent redirect and is cached by browsers)

Upvotes: 1

Related Questions