Nginx on Raspberry Pi 5: Allowing Streaming and Download of Videos

Abstract: Configure Nginx on Raspberry Pi 5 to enable video streaming and downloads using sendfile, tcp_nodelay, and range requests for efficient playback.

Created: 2026-09-29 by
Configure Nginx on Raspberry Pi 5 to serve videos by enabling HTTP Live Streaming (HLS) support and optimizing the sendfile directive. This setup ensures smooth playback for streaming clients while allowing standard file downloads for users who prefer local copies, leveraging the Pi’s efficient I/O capabilities.

Understanding HLS and Nginx Configuration

The most robust method for video streaming on a resource-constrained device like the Raspberry Pi 5 is using HTTP Live Streaming (HLS). Unlike direct MP4 serving, HLS breaks video into small chunks (.ts files) and uses an index file (.m3u8). This allows adaptive bitrate streaming and prevents the server from needing to buffer entire large files in memory before sending them.

Nginx does not stream HLS natively out of the box without specific module configurations or third-party modules like nginx-rtmp-module, but for simple static file serving with download capability, we can optimize the default configuration. The goal is to allow ranged requests, which enable browsers to request specific byte ranges of a video file rather than downloading it sequentially from the start. This is crucial for seeking within a video during playback.

Optimizing Nginx for Video Serving

To allow both streaming and downloading, you must configure the server block in your Nginx configuration file, typically located at /etc/nginx/sites-available/default. The following directives are critical for performance on the Raspberry Pi 5:

  • sendfile on: This enables the use of the sendfile() system call, which transfers data directly from disk to the network socket without copying it through user space. This reduces CPU overhead significantly.
  • tcp_nopush on: Combined with sendfile, this optimizes the amount of data sent in one packet, reducing network overhead.
  • tcp_nodelay on: This disables Nagle's algorithm, ensuring that small packets of data (like video headers or control signals) are sent immediately without waiting to fill a packet.

Additionally, you should set appropriate MIME types. Ensure that types { ... } includes video/mp4 mp4; and application/vnd.apple.mpegurl m3u8; if you are using HLS. Without correct MIME types, browsers may attempt to download the video instead of playing it in the player.

server {
    listen 80;
    server_name localhost;

    root /var/www/html/videos;
    index index.html;

    # Enable sendfile for high-performance static file serving
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;

    # Increase keepalive timeout to handle long-lived video connections
    keepalive_timeout 65;

    location /videos/ {
        # Allow range requests for seeking in video players
        autoindex off;
        
        # Optional: Limit rate if you have bandwidth constraints
        # limit_rate 1M; 

        # Add CORS headers if accessing from different domains
        add_header 'Access-Control-Allow-Origin' '*';
    }

    error_page 404 /404.html;
}

Handling Large Files and Buffering

The Raspberry Pi 5 has ample RAM compared to previous generations, but managing large video files still requires care. If you are serving very large MP4 files (over 1GB), consider increasing the client_max_body_size if you also need to upload videos via the same server. However, for pure serving, the default is usually sufficient.

A common issue is buffering delays. If videos start slowly, check the proxy_buffering setting. If you are behind a reverse proxy or using caching, ensure that proxy_buffering off; is used for video streams to prevent Nginx from buffering the entire response before sending it to the client. For direct static file serving as shown above, this is less relevant, but keeping it in mind helps when integrating with other services.

If you encounter issues with video playback on mobile devices, ensure that the video codec is widely supported (H.264 for video, AAC for audio). Modern browsers and iOS Safari require H.264/AAC for reliable HTML5 video playback. If your videos are in other formats, you may need to transcode them using FFmpeg before placing them in the Nginx directory.

Testing and Verification

After updating your Nginx configuration, always test for syntax errors with sudo nginx -t. If the test passes, reload the service using sudo systemctl reload nginx.

To verify that streaming works correctly, open your browser and navigate to the video URL. Use the developer tools (Network tab) to inspect the requests. You should see multiple requests for byte ranges (HTTP 206 Partial Content) as you scrub through the video timeline. If you see only a single HTTP 200 OK request for the entire file, your sendfile or range request handling might be misconfigured, or the video player is falling back to a non-range-based mode.

For downloading, simply clicking the link should trigger the browser's download manager or play the video inline depending on the browser settings. To force a download instead of inline playback, you can add the header add_header Content-Disposition 'attachment'; inside the location block, though this is often unnecessary for general video hosting where inline playback is preferred.

Related Resources

If you are looking to reduce latency for live streams rather than pre-recorded videos, you might find Minimizing Startup Latency for DASH Livestream with FFmpeg and Nginx useful for more advanced streaming setups. Additionally, if you are running other services alongside your video server, consider reviewing Installing Nginx Proxy Manager on Raspberry Pi with OMV Already Installed for better management of multiple web applications.

Frequently Asked Questions

Why do my videos buffer constantly on the Raspberry Pi?

Buffering is often caused by insufficient bandwidth or high CPU usage during transcoding. Since you are serving static files, ensure you are not transcoding on the fly. Check your network speed and verify that sendfile is enabled to minimize CPU overhead.

Can I serve MKV files directly with Nginx?

Nginx can serve MKV files as static content, but most browsers cannot play MKV natively. You should convert MKV files to MP4 (H.264/AAC) using FFmpeg before placing them in the served directory to ensure compatibility across all devices.

How do I restrict access to video files?

You can implement basic authentication using the auth_basic directive in your Nginx configuration. Alternatively, for more complex access control, integrate with a backend application or use signed URLs if you are using a cloud storage backend.

What is the maximum file size Nginx can handle?

Nginx can handle extremely large files limited only by the filesystem and available disk space. The default client_max_body_size is 1MB, but this applies to uploads. For serving files, there is no hard limit, but ensure your network interface and SD card/eMMC write speeds are not bottlenecks.

Does HTTPS affect video streaming performance?

HTTPS adds encryption overhead, which can slightly increase CPU usage. On the Raspberry Pi 5, this impact is minimal due to its powerful processor. However, ensure your SSL certificates are properly configured to avoid handshake delays that can cause initial buffering.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More