WebDevelopment

Solving Mixed Content Warnings: An Essential Guide for Web Developers with Best Practices

Enhance your website's security and performance by resolving mixed content warnings. Discover best practices to maintain a secure, reliable web presence.

October 5, 2025
mixed content web security HTTPS web development developer guide security best practices site performance
13 min read

Why Mixed Content Warnings Matter (More Than You Think)

You’ve migrated your site to HTTPS. Your certificate is valid. Yet your browser’s console screams: “Mixed content.” If you’ve ever seen this warning, you’re looking at a security gap that undermines the integrity of your page, confuses users, and can harm performance and SEO.

Mixed content happens when an HTTPS page loads any resource over HTTP (insecure). That resource could be a script, stylesheets, fonts, images, iframes, videos, or even network requests made via JavaScript. The implications range from subtle broken images to critical script blocking that breaks functionality and exposes users to man-in-the-middle tampering.

This guide walks you through exactly what mixed content is, why it matters, how to detect it quickly, and the best practices to permanently fix it—complete with practical examples and copy-pasteable configs.


What Is Mixed Content?

When a web page is served over HTTPS but includes subresources over HTTP, the page becomes “mixed.” Browsers split mixed content into two types:

  • Active mixed content: Modifies page behavior and can compromise the entire page. Examples: scripts, iframes, XHR/fetch/WebSocket connections, stylesheets.
  • Passive mixed content: Doesn’t directly modify behavior but can still be tampered with. Examples: images, audio, video.

Modern browsers increasingly auto-upgrade or block mixed content:

  • Active mixed content is typically blocked by default.
  • Passive mixed content may be auto-upgraded to HTTPS; if the upgrade fails, it may be blocked.

Bottom line: Mixed content degrades trust and can break your site in unpredictable ways.


Why You Should Fix Mixed Content Immediately

  • Security: HTTP resources can be intercepted, modified, or replaced, even on “secure” pages.
  • Integrity: An attacker who modifies a script or stylesheet loaded via HTTP can hijack the entire page.
  • UX and reliability: Browsers often block insecure resources, causing broken layouts, missing fonts, or nonfunctional features.
  • Performance: Redirect chains (HTTP → HTTPS) add latency and can lead to longer load times.
  • SEO and compliance: HTTPS is a baseline ranking signal; mixed content undermines credibility. Some compliance regimes require strict HTTPS integrity.

How Browsers Signal Mixed Content

  • DevTools Console: Shows warnings/errors with the resource URL and type.
  • Security Panel (Chrome): Highlights “Mixed Content” with details.
  • Network Panel: Filters allow you to view blocked or downgraded requests; use the “blocked” or “mixed-content” filters when available.
  • Address Bar Icons: A “Not fully secure” message or warning icon may appear.

The trend is toward stricter enforcement and auto-upgrading. Don’t rely on leniency across browsers.


Common Causes of Mixed Content

  • Hardcoded http:// URLs in:
    • HTML (script, link, img, video, audio, iframe)
    • CSS (background images, @font-face src)
    • JavaScript (fetch, XHR, WebSocket, image sources)
  • Third-party embeds and widgets (maps, video players, social scripts)
  • CMS content (posts/pages) and theme templates
  • Environment-specific base URLs (staging vs production)
  • Dynamically generated URLs (server-side rendering, templating)
  • Configuration drift across CDN/proxy layers
  • API endpoints that don’t support HTTPS
  • WebSockets using ws:// instead of wss://
  • Fonts served from an origin without HTTPS or correct CORS headers

Quick Wins: How to Detect Mixed Content Fast

  1. Use the browser:

    • Open DevTools → Console on your HTTPS page and refresh. Look for “Mixed Content” messages.
    • Check the Security panel for details and upgrade suggestions.
  2. Scan your codebase:

    • Grep for http:// patterns:
      # Search HTML, CSS, JS, templates for plain http:// URLs
      grep -RIn "http://" ./src ./public ./templates
      
    • Include file types like .css, .scss, .less, .js, .ts, .html, .twig, .php, .erb, .liquid, .xml (sitemaps), .json (manifests).
  3. Lighthouse and CI:

    • Run Lighthouse locally or via Lighthouse CI to flag insecure resources.
    • Integrate link/mixed-content checkers in CI (e.g., GitHub Actions with a headless browser script).
  4. CSP Reporting (safe, non-breaking):

    • Add a report-only Content Security Policy to detect insecure requests without blocking:
      Content-Security-Policy-Report-Only: upgrade-insecure-requests; report-to csp-endpoint
      Report-To: {"group":"csp-endpoint","max_age":10886400,"endpoints":[{"url":"https://reports.example.com/csp"}]}
      
    • This will surface attempted insecure loads in your reporting endpoint.

Practical Examples of Mixed Content (and Fixes)

HTML (scripts/styles):

<!-- Problem -->
<link rel="stylesheet" href="http://cdn.example.com/styles.css">
<script src="http://cdn.example.com/app.js"></script>

<!-- Fix -->
<link rel="stylesheet" href="https://cdn.example.com/styles.css">
<script src="https://cdn.example.com/app.js"></script>

Images and media:

<!-- Problem -->
<img src="http://images.example.com/hero.jpg">

<!-- Fix -->
<img src="https://images.example.com/hero.jpg">

Avoid protocol-relative URLs (//example.com/...). Historically useful, now discouraged. Prefer explicit https:// for clarity and security.

CSS backgrounds and fonts:

/* Problem */
.hero { background-image: url('http://assets.example.com/bg.jpg'); }
@font-face {
  font-family: 'Acme';
  src: url('http://fonts.example.com/acme.woff2') format('woff2');
}

/* Fix */
.hero { background-image: url('https://assets.example.com/bg.jpg'); }
@font-face {
  font-family: 'Acme';
  src: url('https://fonts.example.com/acme.woff2') format('woff2');
}

JavaScript fetch/XHR:

/* Problem */
fetch('http://api.example.com/v1/data').then(...);

/* Fix */
fetch('https://api.example.com/v1/data').then(...);

WebSockets:

/* Problem */
const ws = new WebSocket('ws://stream.example.com/socket');

/* Fix */
const ws = new WebSocket('wss://stream.example.com/socket');

Iframes:

<!-- Problem -->
<iframe src="http://widgets.partner.com/embed"></iframe>

<!-- Fix -->
<iframe src="https://widgets.partner.com/embed" loading="lazy" referrerpolicy="no-referrer"></iframe>

Sitemaps and canonicals:

<!-- Problem -->
<link rel="canonical" href="http://www.example.com/page">
<!-- Fix -->
<link rel="canonical" href="https://www.example.com/page">

Server-Side Best Practices and Configs

1) Redirect HTTP → HTTPS (but don’t rely on this alone)

You should force HTTPS for all traffic. However, redirects don’t prevent mixed content inside pages—fix URLs at the source.

  • Apache (.htaccess or vhost):

    RewriteEngine On
    RewriteCond %{HTTPS} !=on
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
  • Nginx:

    server {
      listen 80;
      server_name example.com www.example.com;
      return 301 https://$host$request_uri;
    }
    

2) Enable HSTS

HTTP Strict Transport Security tells browsers to always use HTTPS for your domain.

Strict-Transport-Security: max-age=31536000; includeSubDomains; preload

Caution: Preload is powerful; ensure all subdomains support HTTPS before submitting to the preload list.

3) Use CSP to enforce or assist

  • Strong policy during rollout (non-breaking first):

    Content-Security-Policy-Report-Only: upgrade-insecure-requests
    

    This automatically upgrades http:// requests to https:// in the browser and logs reports.

  • Enforce:

    Content-Security-Policy: upgrade-insecure-requests
    

    Pair with carefully defined script-src, style-src, img-src, connect-src to restrict origins.

  • Optionally, block all mixed content explicitly:

    Content-Security-Policy: block-all-mixed-content
    

    Note: Modern browsers already block active mixed content; this directive clamps down further.

4) CDN and proxy configuration

  • Make sure your CDN supports HTTPS for your custom domain (use TLS certs via Let’s Encrypt or provider-issued).
  • Avoid using S3 “website endpoints” (which are HTTP-only) directly on HTTPS pages. Serve through CloudFront (or another CDN) with HTTPS and a proper certificate.
  • Normalize origin protocols to HTTPS in edge rules if possible, but fix the source URLs too.

CMS and Framework-Specific Guidance

WordPress

  • Update Home and Site URL (Settings → General) to https://.
  • Search/replace old URLs in content and serialized data:
    wp search-replace 'http://example.com' 'https://example.com' --all-tables
    
  • Update theme and plugin files for hardcoded http:// references.
  • Ensure media library items use https URLs.
  • If you use page builders, re-save content to refresh URLs.

Drupal

  • Set base_url to https in settings.php if used.
  • Use a search/replace module or Drush to update links in nodes/blocks.
  • Verify theme templates and libraries (libraries.yml) reference https.

Magento/Adobe Commerce

  • Set “Base URL” and “Base URL (Secure)” to https in Stores → Configuration → Web.
  • Clear caches and reindex.
  • Update static content deployment pipeline to ensure https absolute URLs.

Static site generators (Next.js, Gatsby, Hugo)

  • Centralize a SITE_URL env var set to https:// in production.
  • Audit plugin configurations (sitemaps, manifests, RSS) for https.
  • Ensure image/CDN plugins are configured for https origins.

Handling APIs, WebSockets, and CORS

  • Ensure your API endpoints support HTTPS. If you terminate TLS at a load balancer, make sure the backend trusts X-Forwarded-Proto for secure redirects.

  • Update client-side code to use https endpoints. Do not proxy insecure third-party APIs unless absolutely necessary.

  • CORS for fonts and APIs:

    • Fonts often require:
      Access-Control-Allow-Origin: *
      
      or a specific origin, to avoid CORS errors when served from CDNs.
    • For fetch/XHR:
      • Configure your API’s CORS policy to allow your site’s origin over HTTPS.
  • WebSockets:

    • Use wss://.
    • Ensure the server supports TLS and correct ALPN/ciphers.
    • At CDN/edge, enable WebSocket proxying over TLS.

Third-Party Resources and Embeds

  • Always use the provider’s https embed code. Most modern platforms default to https.
  • If a third party still only offers http:
    • Ask for https support or find an alternative provider.
    • As a temporary measure, self-host the asset securely (respecting licenses).
    • You can proxy via your domain over https, but understand the risks:
      • You become responsible for caching, availability, CORS, and potential legal/licensing constraints.
      • Add integrity checks and strict CSP if possible.

Automated Detection in CI/CD

Automate checks so mixed content never reaches production:

  • Headless browser script (Puppeteer/Playwright) that:

    • Loads critical pages.
    • Scrapes console logs for “Mixed Content.”
    • Fails the build on detection.
  • Example (Node + Puppeteer):

    const puppeteer = require('puppeteer');
    
    (async () => {
      const urls = ['https://example.com', 'https://example.com/about'];
      const browser = await puppeteer.launch();
      const page = await browser.newPage();
      let hasMixed = false;
    
      page.on('console', msg => {
        if (msg.text().includes('Mixed Content')) {
          hasMixed = true;
          console.error(msg.text());
        }
      });
    
      for (const url of urls) {
        await page.goto(url, { waitUntil: 'networkidle0' });
      }
    
      await browser.close();
      if (hasMixed) {
        process.exit(1);
      }
    })();
    
  • Lighthouse CI: Integrate into CI and set budgets/policies that fail on mixed content issues.

  • Static scanning: Grep for http:// as part of pre-commit hooks (Husky + lint-staged).


Performance Considerations

  • Redirect chains increase TTFB and degrade Core Web Vitals. Fix root URLs instead of relying on auto-redirects or upgrade-insecure-requests.
  • Consolidate asset domains to reduce TLS handshakes; use HTTP/2 or HTTP/3 on CDNs.
  • Preconnect and preload securely:
    <link rel="preconnect" href="https://cdn.example.com" crossorigin>
    <link rel="preload" href="https://cdn.example.com/styles.css" as="style">
    
  • Use Subresource Integrity (SRI) for third-party scripts/styles:
    <script src="https://cdn.example.com/lib.js"
            integrity="sha384-...hash..."
            crossorigin="anonymous"></script>
    
    SRI helps ensure content integrity even over https.

Edge Cases You Shouldn’t Miss

  • CSS imports and URLs: @import statements or url() inside CSS often slip through audits.
  • Source maps: Some tooling emits http:// URLs in sourceMappingURL; update configurations.
  • Manifests and icons: webmanifest, favicons, app icons may contain http paths.
  • Emails and transactional templates: Links embedded in emails should be https to avoid mixed content when rendered in apps with webviews.
  • Service Workers: Cached HTTP assets can resurface. Invalidate caches when migrating to https and ensure the SW script itself is served over https.
  • Data URLs vs remote resources: Data URIs are fine. Don’t confuse them with http links.
  • Canonicals, Open Graph, Twitter Cards: Ensure all meta URLs are https.
  • Sitemap and robots.txt: Include https links.

Step-by-Step Remediation Plan

  1. Inventory

    • List all page templates and critical user journeys.
    • Include all subdomains and environments (staging, production, edge domains).
  2. Detect

    • Use browser DevTools console and Lighthouse to capture visible issues.
    • Run codebase-wide grep for http:// references.
    • Enable CSP Report-Only with upgrade-insecure-requests, collect reports.
  3. Prioritize

    • Fix active mixed content first (scripts, styles, XHR, WebSockets).
    • Then passive (images, audio/video, iframes).
  4. Remediate at Source

    • Update code, templates, environment variables to https.
    • Replace protocol-relative URLs with explicit https://.
    • Update CMS base URLs and perform content search/replace.
  5. Server and Edge

    • Enforce 301 HTTP → HTTPS.
    • Add HSTS (consider includeSubDomains and preload carefully).
    • Configure CDN/edge for TLS and correct origin protocols.
  6. Reinforce with Policies

    • Start with CSP Report-Only upgrade-insecure-requests.
    • Move to enforced upgrade-insecure-requests.
    • Optionally add block-all-mixed-content after verification.
  7. Validate and Monitor

    • Clear caches (browser, CDN, service worker).
    • Re-run Lighthouse and CI checks.
    • Monitor CSP reports for regression.
  8. Automate

    • Add pre-commit and CI checks to prevent future mixed content.
    • Document standards in your engineering handbook.

Real-World Scenarios and Fixes

  • Scenario: S3 static site with custom domain

    • Problem: Using S3 website endpoint (HTTP only) in asset URLs on an HTTPS page.
    • Fix: Serve the bucket via CloudFront with an SSL cert. Update asset URLs to https://cdn.example.com/path.
  • Scenario: API behind a load balancer

    • Problem: Client fetches http://api.example.com because TLS terminates at the LB, backend is HTTP.
    • Fix: Expose the LB’s HTTPS endpoint publicly, ensure backend remains internal. Update client to https://api.example.com. Configure CORS for https origin.
  • Scenario: Legacy analytics script

    • Problem: Vendor still serves only http script.
    • Fix: Replace vendor or self-host a version you can serve over https (verify license and integrity). Use SRI and CSP to constrain.
  • Scenario: Fonts 404ing on HTTPS

    • Problem: Fonts on CDN missing CORS headers cause blocked loads.
    • Fix: Set Access-Control-Allow-Origin: * (or specific origins), ensure https URLs, and use crossOrigin attributes where needed.

Testing Tips Before and After Deployment

  • Test with the network offline/slow 3G conditions to catch redirect overhead or failures.
  • Use multiple browsers (Chrome, Firefox, Safari) and devices.
  • Clear caches:
    • Service workers: chrome://serviceworker-internals or Application tab in DevTools.
    • CDN: Purge by URL and by cache keys.
  • Inspect the entire request waterfall in the Network panel for unexpected http hops.
  • Run a scripted crawl of key pages with a headless browser to detect any mixed-content console messages.

Frequently Asked Questions

  • Should I use protocol-relative URLs (//example.com)?

    • No. Prefer explicit https://. Protocol-relative URLs add ambiguity and can cause edge-case issues.
  • Can I rely solely on upgrade-insecure-requests?

    • It helps, but don’t treat it as a permanent fix. Update source URLs to https to avoid browser-dependent behavior and redirects.
  • Is mixed content a ranking factor?

    • Not directly, but it undermines security signals, creates broken UX, and can indirectly affect performance and SEO. It’s also a trust issue with users.
  • Do images really matter as much as scripts?

    • Passive mixed content is less dangerous than active, but still a risk. Modern browsers may auto-upgrade images; if upgrade fails, they may be blocked, breaking UI.

A Maintainable Strategy for the Long Term

  • Set a policy baseline: All resources must be requested over HTTPS.
  • Centralize configuration: Use environment variables for API endpoints and CDN base URLs.
  • Keep dependencies current: Outdated libraries and embeds often use old http links.
  • Educate the team: Add mixed content guidelines to code review checklists.
  • Monitor continuously: CSP reports and CI checks catch regressions early.

Final Checklist

  • HTTPS enforced with 301 redirects and HSTS
  • No http:// references in code, templates, or content
  • All third-party embeds and APIs use https (or are self-hosted securely)
  • WebSockets use wss://
  • Fonts served via https with proper CORS headers
  • CSP in place (upgrade-insecure-requests; consider block-all-mixed-content)
  • CI/automation to prevent regressions
  • CDN and storage properly configured for TLS (avoid S3 website endpoints)
  • Service worker and CDN caches cleared after migration

Fixing mixed content is a one-time project—and an ongoing practice. With the steps and tools above, you’ll eliminate warnings, lock down integrity, and deliver a faster, more trustworthy experience for every user.

Share this article
Last updated: October 5, 2025

Related WebDevelopment Posts

Discover more startup know-how and business insights

Strategies for Implementing Polyfills and Fallbacks in 2024:...

Discover powerful methods to implement polyfills and fallbacks ensuring your web...

Mastering 500 Internal Server Error: A Comprehensive Trouble...

Explore real-world scenarios and effective solutions for the 500 Internal Server...

Diagnosing SSL Chain Incomplete Issues: A Step-by-Step Guide...

Discover how to identify and resolve incomplete SSL certificate chain issues wit...

Comprehensive Guide to Handling Browser Rendering Difference...

Master cross-browser compatibility in 2024 with our complete guide to resolving...

Need Expert Help?

Get professional consulting for startup and business growth.
We help you build scalable solutions that lead to business results.