Mixed Content
Imagine you post a letter in a locked, tamper-proof envelope, but inside it you tuck a note that says "also fetch this parcel from the corner stall", and the stall is open for anyone to swap the parcel. The envelope was secure. The parcel was not.
That is mixed content: a page delivered over secure https that loads some of its parts over plain http. The secure part is only as safe as the weakest part.
What You Will Learnβ
- What mixed content is, and why it is dangerous
- The difference between active and passive mixed content
- What browsers block, upgrade, or warn about
- How to find mixed content on a page
- How to fix it, with
httpsaddresses first, and a header as a safety net - What HSTS adds
The Big Ideaβ
https protects a connection from being read or changed on its way. Any part of your page loaded over http has no such protection, and anyone on the path, such as a person on the same public Wi-Fi, can read it or swap it for something else.
- The Code
- Mixed Content Lab
- Mixed Content Finder
<!-- This page is served over https -->
<script src="http://stats.example.net/tracker.js"></script>
<img src="http://images.example.org/photo.jpg" alt="Photo">
<script src="https://stats.example.net/tracker.js" defer></script>
<img src="/images/photo.jpg" alt="Photo">
Content-Security-Policy: upgrade-insecure-requests
| Resource | Kind | What happens |
|---|---|---|
Photo (image)http://images.example.org/photo.jpg | passive | Browser tries an https upgrade, and it loads |
Old banner (image)http://old-ads.example.org/banner.gif | passive | Blocked (the https upgrade failed) |
Video clip (video)http://media.example.net/clip.mp4 | passive | Browser tries an https upgrade, and it loads |
Analytics script (script)http://stats.example.net/tracker.js | active | Blocked |
Legacy widget script (script)http://widgets.example.org/widget.js | active | Blocked |
Stylesheet (stylesheet)http://cdn.example.net/theme.css | active | Blocked |
Map frame (iframe)http://maps.example.net/embed | active | Blocked |
fetch() to an API (fetch)http://api.example.com/data | active | Blocked |
Live updates socket (WebSocket)ws://live.example.com/feed | active | Blocked |
Logo (image)https://www.example.com/logo.png | passive | Loads securely |
Local test script (script)http://127.0.0.1:5500/dev.js | active | Loads (local addresses are treated as trustworthy) |
7 of 11 would fail to load.
A simplified model. Exact behaviour differs a little between browsers and versions, and nothing here loads a real address. The fix is not the header: it is to use https addresses, with the header as a safety net.
Loading the checker...
Why It Is Dangerousβ
What an attacker can do depends on what the page loaded:
- A script over
http: the attacker can replace it with their own. That script then runs inside your secure page, with full access to it, including forms, cookies that are notHttpOnly, and everything the visitor sees. This is as bad as XSS, and it does not need any bug in your code. - A stylesheet over
http: it can hide parts of the page, or reposition a fake form over the real one. - An iframe over
http: the attacker can show a fake page inside your page. - An image or video over
http: it can be swapped for misleading content, and visitors can be tracked, since the request is visible. - A form that submits over
http: everything the visitor typed travels unprotected.
Active and Passive Mixed Contentβ
Browsers split mixed content into two groups, based on how much damage it can do:
| Passive (display) | Active | |
|---|---|---|
| What it is | Content that is shown but cannot change the page | Content that can run or restructure the page |
| Examples | Images, audio, video | Scripts, stylesheets, iframes, fetch and XMLHttpRequest, fonts, WebSockets (ws://) |
| Risk | Lower, but still tamperable and trackable | High: full takeover is possible |
| Typical browser behaviour | Tries to upgrade to https, and blocks it if that fails | Blocked |
Browsers have also been getting stricter over time, and the details differ a little between them. Do not rely on "the browser will fix it". Treat every http address on an https page as a bug.
Links and forms are differentβ
A normal link to an http page is not mixed content, because the visitor is navigating there, not loading it into your page. But it still takes them to an insecure page, so use https when the destination supports it.
A form on an https page that submits to an http address is a different problem. Browsers show warnings, and may block it, because what the visitor types is sent without protection. See Secure Forms.
Finding Mixed Contentβ
- Open the Console. On a page served over
https, DevTools prints messages beginning "Mixed Content:" that name the blocked or upgraded address. - Check the Network panel, and filter by the address starting with
http:. - Search your source code for
http://andws://. Check templates, stylesheets (url(...)), JavaScript strings, and your database content. - Use the Finder tab above on your own markup.
- Check old content. Posts and pages written years ago often hold hard-coded
http://image links.
Fixing Itβ
Step 1: Serve your own site over httpsβ
Your site needs a valid certificate. Many hosts provide this automatically, and free certificate services exist. Redirect every http request to the https version of the same address.
Step 2: Use https addressesβ
Change http:// to https:// for every resource. Most reputable hosts support it. If a host does not, stop using that host, copy the file to your own site if the licence allows, or find an alternative.
Step 3: Prefer relative addresses for your own filesβ
For files on your own site, use paths such as /images/photo.jpg. A relative address always follows the page's scheme, so it cannot be mixed content.
<img src="/images/photo.jpg" alt="Photo">
You may still see old protocol-relative addresses such as //cdn.example.net/lib.js. They work, but writing https:// is clearer, because every site should be on https now.
Step 4: Add the safety netβ
The CSP directive upgrade-insecure-requests tells the browser to rewrite http subresource addresses to https before loading them:
Content-Security-Policy: upgrade-insecure-requests
It is useful when you have a lot of old content to clean up. But it is a net, not a cure:
- If the host does not support
https, the upgraded request simply fails. - It hides the problem. Your source code still contains
http://, and a header change, or a different server, may expose it again.
Open the lab, switch the checkbox on and off, and compare the "Legacy widget script" row. Fix the addresses, then keep the header as a backup. Do not use it as a substitute for fixing them.
Step 5: Add HSTS, carefullyβ
Strict-Transport-Security (HSTS) tells the browser: "for the next while, always use https for my site, even if someone types http://":
Strict-Transport-Security: max-age=31536000; includeSubDomains
HSTS is hard to undo, because browsers remember it for the length of max-age. Turn it on only after your whole site, including subdomains, works over https. Start with a short max-age, such as a day, test, and raise it step by step. Treat the preload option as a long-term commitment, and read the current requirements before using it.
Step 6: Add integrity for third-party filesβ
For scripts and styles from other hosts, the integrity attribute lets the browser check that the file is exactly the one you reviewed. It needs crossorigin for cross-origin files. Details and cautions are in Third-Party Content Security.
<script src="https://cdn.example.net/lib.js"
integrity="sha384-REPLACE_WITH_THE_REAL_HASH"
crossorigin="anonymous"></script>
A Few Related Pointsβ
- WebSockets: use
wss://, notws://, on anhttpspage. - Local development:
http://localhostandhttp://127.0.0.1are treated as trustworthy by browsers, so your local test pages can load localhttpresources. That is why this tutorial's live demos run from an address likehttp://127.0.0.1:5500. Do not leave those addresses in published pages. - Secure contexts: many powerful features only work on
httpspages (and local addresses), such as location, the camera, service workers, and the clipboard. A site that is not onhttpsloses these. This ties to the HTML Security Basics lesson on the https-first rule. - Browser labels: pages served over
httpare marked "Not secure" in current browsers, and visitors notice.
Checking Your Setupβ
- Load your page over
https, open the Console, and reload. There should be no "Mixed Content" messages. - In Network, filter by
http:and confirm nothing is listed. - Visit the
httpversion of your address. It should redirect tohttps. - Inspect the Response Headers for
Strict-Transport-SecurityandContent-Security-Policy. - Search your content database for
http://, and update old links. - Test with a private window, in case a browser extension is hiding a problem.
Best Practicesβ
- Serve the whole site over https, and redirect
httpto it. - Use
https://or relative addresses for every resource. - Treat any
http://on a secure page as a bug, even if a browser upgrades it. - Drop hosts that do not support https.
- Add
upgrade-insecure-requestsas a safety net, not a cure. - Enable HSTS only when everything works, and raise it gradually.
- Use
wss://for WebSockets. - Clean old content, especially hard-coded image links.
- Add
integrityto third-party scripts and styles. - Remove local development addresses before you publish.
Quick Checklistβ
- The site has a valid certificate, and
httpredirects tohttps - No
http://orws://addresses in HTML, CSS, JavaScript, or content - Forms submit to
httpsor relative addresses - The Console shows no "Mixed Content" messages
-
upgrade-insecure-requestsis set as a backup - HSTS is set only after testing
- Third-party files use
https, and ideallyintegrity - No local addresses are left in published pages
Security and Privacy Notesβ
- Insecure requests leak information. An
httprequest shows the address, and often the referrer, to anyone on the path. See noreferrer. - A padlock is not a guarantee of a safe site. It says the connection is encrypted, not that the page is trustworthy. Mixed content weakens even that.
- Public Wi-Fi is where this attack happens. Visitors in cafes, airports, and shared networks are the most exposed.
- Certificates need renewal. An expired certificate breaks your whole site and teaches visitors to click through warnings. Automate renewal, and monitor it.
Global Audience Notesβ
- Some networks and older devices are slow to adapt. Older phones may not trust newer certificates, and some regions still have many
http-only services. Test on realistic devices, and have a plan if a partner site has nohttps. - Shared and public networks are more common in some regions, which makes
httpseverywhere more important there. - Interrupted connections can cause partial loads. A page that mixes secure and insecure resources can break in confusing ways when parts fail. Keep everything on one scheme.
Common Mistakes to Avoidβ
- Hard-coding
http://in templates, stylesheets, or database content. - Relying on browsers to upgrade passive content.
- Using
upgrade-insecure-requestsas the only fix, against a host with no https. - Enabling HSTS before everything works on
https. - Forgetting
ws://, fonts inside CSS, andfetchURLs in JavaScript. - Leaving
localhostaddresses in a published page. - Letting a certificate expire.
- Linking forms to
httpaddresses. - Ignoring Console warnings because "the page still looks fine".
- Testing only your own browser, and not a private window or another device.
Practice Timeβ
- In the Mixed Content Lab, keep the page on
httpswith the header off. Which resources fail, and which are upgraded? - Switch the header on. Which resources still fail, and why?
- Switch the page to
http. What changes? Is that a good result? - Find the local test script in the table. Why does it load?
- Load the messy page in the Mixed Content Finder, and fix every problem until it reports a clean page.
- Open any page of your own site, open the Console, and look for "Mixed Content" messages.
- Search one of your own templates for
http://. How many did you find? - Bonus: write the
Strict-Transport-Securityheader you would use for your first week of testing.
Quick Recapβ
Click a question to check your answer.
1. What is mixed content?
A page served over https that loads some resources, such as scripts or images, over plain http.
2. Why is it dangerous?
Resources loaded over http can be read or replaced by anyone on the path. A swapped script runs inside your secure page.
3. What is the difference between active and passive mixed content?
Passive content, such as images and video, is displayed only. Active content, such as scripts, stylesheets, and frames, can run or change the page, so browsers block it.
4. What is the real fix?
Use https:// or relative addresses for every resource, and serve your own site over https.
5. What does upgrade-insecure-requests do?
It tells the browser to load http subresources over https. It is a safety net, and fails when the host does not support https.
6. When should you enable HSTS?
Only after the whole site, including subdomains, works over https, because browsers remember it for the full max-age. Start with a short value.
Key Takeawaysβ
- Mixed content is an
httpresource on anhttpspage. It breaks the protectionhttpsgives. - Active content is blocked, and passive content may be upgraded or blocked. Do not depend on either.
- Fix addresses first:
https://or relative paths. upgrade-insecure-requestsis a safety net, and HSTS is a commitment to apply with care.- Check the Console, your source, and your old content.
- Local addresses are trusted for testing, but never publish them.
Next up: Secure Forms, where you will learn how to protect what visitors type: submission over https, safe autofill and password fields, and the checks that belong on the server.