Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's correct htaccess rule to redirect mixed content to HTTPS

Is there a way with htaccess redirect conditions and redirects to catch content called over HTTP when the site is accessed via HTTPS?

Such that http content will be redirected to the https equivalent url if the site is accessed over HTTPS?

Essentially I'd like a automated way to mop up and deal with mixed content when my site is accessed via HTTPS.

So far the following fixed all .css and .js files being called over HTTP when site is accessed through HTTPS.

RewriteRule ^/(.*):SSL$   https://%{SERVER_NAME}/$1 [R,L]
RewriteRule ^/(.*):NOSSL$ http://%{SERVER_NAME}/$1 [R,L]

But for some reason this does not redirect requests for images (for instance) on my site being called through HTTP during an HTTPS session.

I also tried this rule,

RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

but that didn't redirect the images either.

I figure there must be a way to test if connection is over HTTPS, then rewrite any http:// urls to an https:// equivalent. I am just not sure how to formula the rules correctly.

like image 424
inspirednz Avatar asked Jan 31 '16 09:01

inspirednz


1 Answers

This won't work.

The browser will see the http request and mark the page as containing insecure content. And rightly so as the request will be made over http, and then redirected to https. So it is insecure because of that.

What you want to do is use Content-Security-Policy to ask the web browser to update the request when it loads the page

Header always set Content-Security-Policy: upgrade-insecure-requests

See here for more info: https://www.w3.org/TR/upgrade-insecure-requests/

Note browser support is mixed for this: https://caniuse.com/upgradeinsecurerequests

like image 163
Barry Pollard Avatar answered Sep 20 '22 13:09

Barry Pollard