Skip to content

Instantly share code, notes, and snippets.

@raikel
Last active November 15, 2020 19:32
Show Gist options
  • Select an option

  • Save raikel/d07bb938fcce63cc43b9bc757a8ea16e to your computer and use it in GitHub Desktop.

Select an option

Save raikel/d07bb938fcce63cc43b9bc757a8ea16e to your computer and use it in GitHub Desktop.
Stream RTMP and HLS video with Nginx
  1. Install nginx RTMP module

sudo apt install libnginx-mod-rtmp

  1. Add the following configuration to /etc/nginx/nginx.conf
rtmp {
        server {
                listen 1935;
                chunk_size 4096;

                application live {
                        live on;
                        record off;
                        # Turn on HLS
                        hls on;
                        hls_path /nginx/hls;
                        hls_fragment 3;
                        hls_playlist_length 60;
                }
        }
}
  1. Create the root directory for HLS files
sudo mkdir /nginx
sudo mkdir /nginx/hls
sudo chown -R www-data:www-data /nginx
  1. Create a new nginx server block at /etc/nginx/sites-available/hls with the following content
server {
        listen 80;
        server_name <server_name>;

        location /hls {
                # Disable cache
                add_header Cache-Control no-cache;

                # CORS setup
                add_header 'Access-Control-Allow-Origin' '*' always;
                add_header 'Access-Control-Expose-Headers' 'Content-Length';

                # allow CORS preflight requests
                if ($request_method = 'OPTIONS') {
                        add_header 'Access-Control-Allow-Origin' '*';
                        add_header 'Access-Control-Max-Age' 1728000;
                        add_header 'Content-Type' 'text/plain charset=UTF-8';
                        add_header 'Content-Length' 0;
                        return 204;
                }

                types {
                        application/vnd.apple.mpegurl m3u8;
                        video/mp2t ts;
                }

                root /nginx;
        }
        
        error_log /var/log/nginx/hls-error.log;
        access_log /var/log/nginx/hls-access.log;
}
  1. Test the configuration and restart the server
sudo nginx -t
sudo systemctl restart nginx
  1. Stream to the RTMP server at the URL rtmp://<server_name>/live/<stream_key>, where <stream_key> is any string you want to use to identify the stream.

  2. Play a RTMP stream using the URL rtmp://<server_name>/live/<stream_key> and a HLS stream at the URL http://<server_name>/hls/<stream_key>.m3u8.

References

https://docs.peer5.com/guides/setting-up-hls-live-streaming-server-using-nginx/ https://www.josedomingo.org/pledin/2020/07/streaming-video-software-libre/ https://www.nginx.com/blog/video-streaming-for-remote-learning-with-nginx/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment