插件窝 干货文章 Nginx如何搭建图片视频服务器

Nginx如何搭建图片视频服务器

Nginx 配置 location image 609    来源:    2025-04-23

Nginx搭建图片视频服务器指南

Nginx是一个高性能的HTTP和反向代理服务器,非常适合用来搭建图片和视频服务器。以下是详细的搭建步骤:

1. 安装Nginx

# Ubuntu/Debian
sudo apt update
sudo apt install nginx

# CentOS/RHEL
sudo yum install epel-release
sudo yum install nginx

# 启动Nginx
sudo systemctl start nginx
sudo systemctl enable nginx

2. 配置图片服务器

基本配置

编辑Nginx配置文件(通常在/etc/nginx/nginx.conf/etc/nginx/conf.d/default.conf):

server {
    listen 80;
    server_name your-domain.com;

    location /images/ {
        alias /path/to/your/images/;
        autoindex on;  # 可选:开启目录列表
        expires 30d;   # 设置缓存时间

        # 图片处理模块(需安装)
        # image_filter resize 150 100;
        # image_filter rotate 90;
    }

    # 防止盗链配置
    location ~* \.(jpg|jpeg|png|gif)$ {
        valid_referers none blocked your-domain.com *.your-domain.com;
        if ($invalid_referer) {
            return 403;
        }
    }
}

优化配置

# 启用gzip压缩
gzip on;
gzip_types image/jpeg image/png image/gif;

# 启用sendfile提高性能
sendfile on;
tcp_nopush on;
tcp_nodelay on;

# 设置客户端最大body大小(上传大图片)
client_max_body_size 20M;

3. 配置视频服务器

基本视频服务

server {
    listen 80;
    server_name video.your-domain.com;

    location /videos/ {
        alias /path/to/your/videos/;

        # 支持视频流
        mp4;
        mp4_buffer_size 1m;
        mp4_max_buffer_size 5m;

        # 支持视频拖拽
        flv;

        # 设置缓存
        expires max;
    }
}

支持HLS流媒体

location /hls/ {
    types {
        application/vnd.apple.mpegurl m3u8;
        video/mp2t ts;
    }
    alias /path/to/hls/files/;
    add_header Cache-Control no-cache;

    # 允许跨域(可选)
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
}

4. 安全配置

# 限制某些文件类型的访问
location ~* \.(php|asp|aspx|jsp)$ {
    deny all;
}

# 防止目录遍历
location ~ /\. {
    deny all;
}

# 限制访问速率
limit_req_zone $binary_remote_addr zone=media:10m rate=10r/s;

location /downloads/ {
    limit_req zone=media burst=20;
}

5. 测试与重载配置

# 测试配置是否正确
sudo nginx -t

# 重载配置
sudo systemctl reload nginx

6. 高级功能(可选)

图片缩略图生成

安装Nginx图像处理模块:

# Ubuntu/Debian
sudo apt install libnginx-mod-http-image-filter

# CentOS/RHEL
sudo yum install nginx-module-image-filter

配置示例:

location ~* /images/(.*)_(\d+)x(\d+)\.(jpg|png|gif)$ {
    set $file $1.$4;
    set $width $2;
    set $height $3;

    image_filter resize $width $height;
    image_filter_buffer 10M;
    image_filter_jpeg_quality 85;

    alias /path/to/images/$file;
}

视频转码与切片

可以使用FFmpeg将视频转换为HLS格式:

ffmpeg -i input.mp4 -codec: copy -start_number 0 -hls_time 10 -hls_list_size 0 -f hls output.m3u8

7. 性能优化建议

  1. 启用Nginx缓存
  2. 使用CDN分发静态内容
  3. 对图片进行WebP格式转换
  4. 对视频使用自适应比特率流
  5. 考虑使用Nginx的X-Accel-Redirect功能保护媒体文件

通过以上配置,您可以搭建一个高性能的图片和视频服务器,满足各种媒体服务需求。