Skip to content
WJunction - Webmaster Forum

How to Set Up HLS Video Streaming with Nginx and FFmpeg (Ubuntu 22.04, step by step)

HLS (HTTP Live Streaming) cuts a video into small segments and lists them in an .m3u8 playlist. It starts fast, works on phones and works behind any CDN. Here is the short version of how to set it up on an Ubuntu 22.04 VPS.

WHAT YOU NEED
- A VPS with Ubuntu 22.04 (1 vCPU and 2 GB RAM is enough to start)
- A domain or subdomain pointing to the server
- An MP4 file you have the right to publish

STEP 1: Install Nginx and FFmpeg

sudo apt update
sudo apt install -y nginx ffmpeg

STEP 2: Convert the MP4 to HLS

sudo mkdir -p /var/www/video/movie1
ffmpeg -i input.mp4 -c:v libx264 -preset veryfast -crf 23 -pix_fmt yuv420p -g 48 -sc_threshold 0 -c:a aac -b:a 128k -hls_time 6 -hls_playlist_type vod -hls_segment_filename "/var/www/video/movie1/seg_%03d.ts" /var/www/video/movie1/index.m3u8
sudo chown -R www-data:www-data /var/www/video

Set -g to twice your frame rate (48 is for 24 fps). If the file is already H.264 video with AAC audio, replace the encoding options with -c copy. It finishes in seconds.

STEP 3: Serve it with Nginx

server {
listen 80;
server_name video.example.com;
root /var/www/video;

location ~* \.m3u8$ {
add_header Cache-Control "no-cache";
add_header Access-Control-Allow-Origin "https://example.com" always;
}
location ~* \.ts$ {
add_header Cache-Control "public, max-age=31536000, immutable";
add_header Access-Control-Allow-Origin "https://example.com" always;
}
}

Playlists are not cached, segments are cached for a long time because they never change. Replace example.com with the site that shows the player.

STEP 4: Turn on HTTPS

sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d video.example.com

An HTTPS page cannot load HTTP video, so this step is required.

STEP 5: Play it
Safari plays HLS natively. Other browsers need the free hls.js library. Point the player at https://video.example.com/movie1/index.m3u8

COMMON PROBLEMS
- CORS error: the Allow-Origin value must match your site exactly, including https and www
- Blocked on an HTTPS page: the video address still starts with http
- 404 on segments: check the folder path and file permissions
- Stuttering: the server upload speed is too low for the bitrate, lower it or put a CDN in front

The full guide also covers the player code, multiple quality levels (720p / 480p) and moving the files to Cloudflare R2:

Questions are welcome below.
 

About the author

Servrix
Active Member · Joined
Linux, WordPress, Nginx, Cloudflare ve e-posta listeleri içerideki Web Yöneticisi ve Sistem Yöneticisi. Performans...
108
Messages
14
Reactions
18
Points

Advertise on WJunction

Reach 1000's of webmasters, hosts & affiliates. Banner & sponsored-thread slots available.

Contact us
Back
Top Bottom