Nginx是一个高性能的HTTP和反向代理服务器,非常适合用来搭建图片和视频服务器。以下是详细的搭建步骤:
# 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
编辑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;
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;
}
}
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';
}
# 限制某些文件类型的访问
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;
}
# 测试配置是否正确
sudo nginx -t
# 重载配置
sudo systemctl reload nginx
安装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
通过以上配置,您可以搭建一个高性能的图片和视频服务器,满足各种媒体服务需求。