How to get Safari to stream self hosted MP4 via Cloudflare
Posted in dailyTags :
Updated in April 2020 to add the
I recently had to remove a bunch of videos served by Vimeo while I searched for an alternate hosting solution. In order to continue to stream these videos, I opted for the simplest solution which was to use the
In a similar manner to the
img element, we include a path to the media we want to display inside the src attribute; we can include other attributes to specify information such as video width and height, whether we want it to autoplay and loop, whether we want to show the browser’s default video controls, etc.
Everything worked fine, except that Safari didn’t play the video, even when accessing it with through a direct URL. After researching a bit, I found out that Safari expects a different status (206 Partial Content) in the file header than the one it was receiving (200 OK).
Video files are different to images or other static content. Video doesn’t want to be loaded in one go. Video should return a 206 Partial Content status in the file header which allows your browser to process larger files that require split or interrupted downloads with multiple simultaneous streams which improves latency.
It was receiving a 200 status code because its content was cached on Cloudflare edge servers.
Thomas James Hole explains what is going on in a post on Stirtingale and suggests to add a Cloudflare page rule to exclude MP4 files from being cached:
https://www.domain.tld/mediapath*/*.mp4* Cache Level: Bypass Cache
But that still didn’t fix my issue, despite having confirmed that the file was no longer being cached.
It took an additional .htaccess Apache directive by Jules to tell the server not to gzip mp4/webm/ogv files:
#To make MP3 streaming on Safari with Cloudflare CF SetEnvIfNoCase Request_URI . (?:mp4|ogv|webm)$ no-gzip dont-vary
And suddenly, all was honky dory again.
April 2020 update : this solution solves media being served through the
audio element too. Add the relevant extensions to the list (e.g. mp3) :
#To make MP3 streaming on Safari with Cloudflare CF SetEnvIfNoCase Request_URI . (?:mp4|ogv|webm|mp3)$ no-gzip dont-vary