Subtitles not working from external URL in HTML element video

0
Hi all, I’m trying to add subtitles to my HTML5 video using an external URL, but it’s not working. The local subtitle files work fine, but when I use a URL from my server or CDN, the subtitles don’t show up in the browser. Here’s an example of my code:   <video width="100%" controls>  <source src="https://example.com/path/to/video.mp4" type="video/mp4">   <track    src="https://example.com/path/to/subtitles_de.vtt"    kind="subtitles"    srclang="de"    label="Deutsch"    default />   <track    src="resources/subtitles_hi.vtt"    kind="subtitles"    srclang="hi"    label="Hindi" />   Your browser does not support the video tag.</video>   What I’ve tried so far: Using relative paths (like resources/subtitles_hi.vtt) works fine. Using the external URL doesn’t work — the subtitles just don’t appear. I checked, and the file is publicly accessible. I think it might be a CORS issue. Does anyone know how I can allow my server/CDN to serve .vtt files so the browser can load them properly? Thanks a lot for any help!
asked
1 answers
0

When you load a <track> from a different domain than your website, the browser treats it as a cross-origin request. By default, browsers block these for security reasons unless the server hosting the subtitles explicitly says, "I allow this."


Here is how to fix it in two steps:


1. Update your HTML


You need to tell the <video> tag to use CORS when fetching resources. Add the crossorigin attribute to your video element:

HTML


<video width="100%" controls crossorigin="anonymous">
  <source src="https://example.com/path/to/video.mp4" type="video/mp4">
  <track 
    src="https://example.com/path/to/subtitles_de.vtt" 
    kind="subtitles" 
    srclang="de" 
    label="Deutsch" 
    default />
</video>

Note: Use crossorigin="anonymous" if the subtitle file doesn't require user credentials (like cookies or HTTP auth) to be accessed.

2. Configure your Server/CDN

The server hosting the .vtt file must return a header that allows your website to read it. You need to add the following header to the response of the .vtt files:

Access-Control-Allow-Origin: * (Or replace * with your specific domain, e.g., https://yourwebsite.com)

How to add this on common servers:

  • Apache (.htaccess):
Apache
<FilesMatch "\.(vtt)$">
    Header set Access-Control-Allow-Origin "*"
</FilesMatch>
  • Nginx:
  • Nginx
location ~* \.vtt$ {
    add_header Access-Control-Allow-Origin *;
}
  • S3 / CloudFront: You must go to the CORS configuration of your S3 bucket and add a rule allowing the GET method for your domain.


Why is this happening?

The browser sends a "Preflight" request (or checks the headers) to ensure the external server trusts your website. If the Access-Control-Allow-Origin header is missing, the browser will silently fail to load the track, even if the file is publicly accessible via a direct link.

answered