Ryall
Ryall

Reputation: 12281

Using 'mod_rewrite' how do I force HTTPS for certain paths and HTTP for all others?

I have a PHP-Apache application using mod_rewrite for clean URLs. I am having a lot of touble getting certain pages and paths forced to HTTPS while also ensuring all others will remain as HTTP.

Here is an example of what I mean:

// http://www.example.com/panel/ -> Should always redirect to HTTPS
// http://www.example.com/store/ -> Should always redirect to HTTPS

// Anything not in the above should always be HTTP
// so...
// https://www.example.com/not-in-above-rules -> Should always redirect to HTTP

Any ideas?

Upvotes: 3

Views: 6816

Answers (4)

toastyghost
toastyghost

Reputation: 51

None of these solutions works with pretty url's. One suggestion: we were getting browser security warnings just using the http_host in the rewrite. Evidently, Thawte is retarded and therefore prefixing with 'www' or not makes a difference as to the perceived validity of the certificate. Here are a few lines to ensure that redirects to the secure site are always prefixed with 'www':

RewriteCond %{HTTP_HOST} ^www\.mysite\.com [NC]
RewriteRule ^(login\.php|members\.php)$ https://%{HTTP_HOST}%{REQUEST_URI}
RewriteCond %{HTTP_HOST} ^mysite\.com [NC]
RewriteRule ^(login\.php|members\.php)$ https://www.${HTTP_HOST}%{REQUEST_URI}

Or to do it in a little less space, you could drop the 2nd line and hard-code the domain in the 4th. I'm sure there's a more elegant way of doing it, but htaccess is frustrating, and this works.

Upvotes: 0

tersmitten
tersmitten

Reputation: 1330

You can put something like this in your :80 vhost:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(panel/|store/payment) https://%{HTTP_HOST}%{REQUEST_URI}

And this in your :443 vhost:

RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule !^(panel/|store/payment) http://%{HTTP_HOST}%{REQUEST_URI}

Upvotes: 10

yfeldblum
yfeldblum

Reputation: 65435

The general rule of good security is: if some of your site requires HTTPS, then all of your site requires HTTPS. If you will be using HTTPS in the payment section, then your landing page should be HTTPS as well.

Upvotes: 2

Ass3mbler
Ass3mbler

Reputation: 3915

to do it:

RewriteCond %{HTTP_HOST}         ^www.example.com(:80)?$

RewriteRule ^/panel/(.*) https://www.example.com/panel/$1 [R=301,L]

the same for the other path

Hope it helps

Upvotes: 0

Related Questions