Fix Varnish Broken CSS Mixed Content Errors CloudFlare Flexible SSL

CloudFlare Flexible SSL provides a free SSL certificate for WordPress and WooCommerce sites. Flexible SSL encrypts the connection between your visitor and CloudFlare providing the green lock in web browsers which signals trust. For login forms and checkout consider using Full SSL instead.

If using Flexible SSL with Varnish you may find visitors get broken CSS on the https versions of your pages if your site url is set to http. There is a simple fix which will solve your mixed content problems for both Varnish 3 and 4.

CloudFlare sets a header for the protocol to be used with the X-Forwarded-Proto header. This header can be used by Varnish to cache different versions of pages and posts based on this header. In essence each post or page will have two versions in the Varnish cache: one for http version and one for https version.

Ideally you should install the CloudFlare Flexible SSL plugin as well, which catches the X-Forwarded-Proto header and can also be the cause of broken CSS with Varnish or another reverse proxy.

Fix Varnish Broken CSS Mixed Content Errors CloudFlare Flexible SSL

This fix will work on both Varnish 3 and Varnish 4

Fix Broken CSS Errors with CloudFlare Flexible SSL Running Varnish 3

Open your Varnish 3 vcl

sudo nano /etc/varnish/default.vcl

Add this section into sub vcl_hash, just add the whole section if it doesn't exist

sub vcl_hash {

    if (req.http.X-Forwarded-Proto) {
        hash_data(req.http.X-Forwarded-Proto);
    }
}

Test your Varnish 3 vcl

sudo varnishd -C -f /etc/varnish/default.vcl

If you saw no errors then reload Varnish 3

sudo service varnish reload

Fix Broken CSS with CloudFlare Flexible SSL Running Varnish 4

Open your Varnish 4 vcl

sudo nano /etc/varnish/default.vcl

Similar to Varnish 3, add this section into sub vcl_hash, again add the whole section if it doesn't exist

sub vcl_hash {

    if (req.http.X-Forwarded-Proto) {
        hash_data(req.http.X-Forwarded-Proto);
    }
}

Test your Varnish 4 vcl

sudo varnishd -C -f /etc/varnish/default.vcl

If you saw no errors then reload Varnish 4

sudo service varnish reload

Now you may get a yellow triangle warning in Google Chrome or Firefox but the CSS appearance of your WordPress or WooCommerce site will now look normal. No more mixed content errors.