Using 'mod_rewrite' how do I force HTTPS for certain paths and HTTP for all others?
I ha开发者_如何学编程ve 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?
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}
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.
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
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.
精彩评论