Force redirect to SSL for all pages apart from one

2020-02-11 12:21发布

问题:

I'm trying to use apache2's mod_rewrite to force SSL connections to a website. So far, it's working fine with the following in the site's <VirtualHost> entry :

RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [QSA,NC,R,L]

This is working well, and redirects everything, which is what I wanted.

However, there's one particular page on the site which uses the Google maps API, which isn't available over SSL and hence triggers mixed content warnings in the browser. So, I'd like this one, map-only page not to redirect, and use the normal, non-ssl connection.

The URL that I don't want SSL on has the form /thing/add/{ID}/page3 where {ID} is a numeric value.

Is this possible?

回答1:

RewriteEngine On

RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^thing/add/\d+/page3$ - [L]

RewriteCond %{SERVER_PORT} ^443$
RewriteRule ^(thing/add/\d+/page3) $ http://%{HTTP_HOST}/$1 [QSA,NC,R,L]

RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [QSA,NC,R,L]

The rules are processed top to bottom; the first one stops rewrite for maps page if not on SSL; the second one (optional) redirects these pages to non-secure if accessed via SSL; for all else, the old rule applies.