通过 nginx 设置外部访问服务器视频

本文记录通过 nginx 设置外部访问服务器视频的过程。

添加一个 video.conf配置文件,用于放 mp4 文件 Nginx 配置(假设视频放在 /example/video/ 目录下)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 编辑配置文件
vim /usr/local/nginx/conf/video.conf
# 配置文件内容
location /video/ {
alias /example/video/;

mp4;
mp4_buffer_size 4m;
mp4_max_buffer_size 20m;

sendfile on;
tcp_nopush on;

# 启用范围请求
add_header Accept-Ranges bytes;

# 缓存控制
expires 30d;
add_header Cache-Control "public, max-age=604800";

# 限速
limit_rate_after 10m;
limit_rate 2m;
}

配置完成后,在主配置文件中引用该配置

1
2
3
4
5
6
7
8
9
10
11
12
13
server {
listen 80;
server_name your-domain.com;

location /app1 {
# 其他配置...
}

location /app2 {
# 其他配置...
}
include /usr/local/nginx/conf/video.conf
}

重启 nginx

1
systemctl restart nginx

如果报如下信息测试失败,那可能是因为你的 nginx 没有安装 mp4 模块,该模块不会默认安装

nginx: [emerg] unknown directive “mp4” in /usr/local/nginx/conf/video.conf:5
nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed

由于我的 nginx 是编译安装的,重新编译 nginx,查看目前的编译参数

1
/usr/local/nginx/sbin/nginx -V

如果有之前已经编译过的模块,重新编译时也要记得加上,例如下面的 ssl 模块

1
2
3
./configure  --with-http_ssl_module --with-http_mp4_module
make
make install

编译完成后,重新启动 nginx 就可以通过 your-domain.com/video/video.mp4 访问了。

参考资料