Easily fixing insecure references

One of the easiest mistakes to make when trying to convert an insecure HTTP website over to a secure HTTPS one is mixed content.

Mixed content is when the site itself is loaded over HTTPS, but it contains links to content which are HTTP and therefore insecure – there’s no point knowing that the page itself has been secured if it is loading content which isn’t, which is why the browser flags this.

For an example, check out BadSSL’s mixed content demo page and the slightly more severe mixed content script demo page – the later tries to load a javascript file insecurely, which the browser really doesn’t like.

So how do we fix this problem?  Obviously the longer term goal is to replace in the code of your website all of the “http://” references to “https://”, but this can be time consuming and troublesome.  What if you’re using a third party library or API which is only hosted on HTTP?  (Hint: Stop using it if you can!).

The primary part of the fix is to use a Content Security Policy (CSP) directive to instruct the browser that you wish to upgrade all requests from HTTP to HTTPS.  This can be added as a meta tag in your source code…

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">

However, I wouldn’t recommend doing it this way – personally I add it to my .htaccess file (Apache server) using the following lines…

<IfModule mod_headers.c>
  Header set Content-Security-Policy "upgrade-insecure-requests"
  Header set X-Content-Security-Policy "upgrade-insecure-requests"
</IfModule>

As you can see this adds the header with the same directive, “upgrade-insecure-requests”.  This also sets “X-Content-Security-Policy” for the benefit of older Internet Explorer versions.

Having done that, you can also go into your Cloudflare dashboard, assuming that you’re using Cloudflare, go to the Crypto tab and set the following settings…

  • Automatic HTTPS Rewrites – this helps fix mixed content by changing “http” to “https” for all resources or links on your web site that can be served with HTTPS
  • Always Use HTTPS – this redirects all requests with scheme “http” to “https”, in case someone types the HTTP link into the browser

Between your CSP and your Cloudflare configuration, your website visitors should never see mixed content warnings again.

Troy Hunt covered this in his own HTTP Is Easy course, which is well worth checking out if you’re doing this.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.