본문 바로가기

Server/Ubuntu

[Ubuntu] Nginx 에서 HTTP Live Streaming(HLS)설정 스크립트.

반응형

Nginx에서 HTTP Live Streaming(HLS)을 설정하기 위한 스크립트입니다.

#!/bin/bash

# Check if Nginx is installed
if [ ! -f /usr/sbin/nginx ]; then
    echo "Nginx is not installed. Please install Nginx and try again."
    exit 1
fi

# Install required packages
sudo apt-get update
sudo apt-get install -y ffmpeg

# Get the domain name
echo -n "Enter the domain name (e.g. example.com): "
read domain

# Check if the domain name is valid
if [ -z "$domain" ]; then
    echo "Invalid domain name."
    exit 1
fi

# Create the domain directory
sudo mkdir -p /var/www/$domain/public_html

# Set the ownership and permissions for the domain directory
sudo chown -R $USER:$USER /var/www/$domain/public_html
sudo chmod -R 755 /var/www/$domain

# Create the virtual host file for the domain
sudo tee /etc/nginx/sites-available/$domain <<EOF
server {
    listen 80;
    server_name $domain www.$domain;
    root /var/www/$domain/public_html;
    index index.html;
    location /hls/ {
        # Serve HLS segments
        add_header Cache-Control no-cache;
        types {
            application/vnd.apple.mpegurl m3u8;
            video/mp2t ts;
        }
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
        add_header 'Access-Control-Allow-Headers' 'Range';
        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;
        }
        if (\$request_method = 'GET') {
            if (\$http_range) {
                add_header 'Content-Length' '';
                add_header 'Accept-Ranges' 'bytes';
                add_header 'Content-Range' "\$http_range/\$upstream_http_content_length";
                add_header 'Access-Control-Allow-Origin' '*';
                return 200;
            }
            if (-f \$request_filename) {
                add_header 'Content-Length' \$upstream_http_content_length;
                add_header 'Accept-Ranges' 'bytes';
                add_header 'Access-Control-Allow-Origin' '*';
                return 200;
            }
        }
        return 404;
    }
}
EOF

# Create a symbolic link to the virtual host file in the sites-enabled directory
sudo ln -s /etc/nginx/sites-available/$domain /etc/nginx/sites-enabled/

# Restart Nginx to apply the changes
sudo systemctl restart nginx
반응형