[英]How to serve part of a file with Nginx?
我正在使用X-Accel提供受保護的內容,使用 X-Accel-Redirect。
是否可以只提供文件的一部分? 例如,字節范圍為 0-x,或視頻的前 5 分鍾(我的最終目標)
在服務器端執行此操作很重要,因此客戶端將無法訪問文件的 rest。
目前這是我發送整個文件的方式:
X-Accel-Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
Content-Type: application/octet-stream
Content-Length: {file_size}
Content-Disposition: attachment; filename="myfile.mp4"
Accept-Ranges: bytes
X-Accel-Buffering: yes
X-Accel-Redirect: /protected/myfile.mp4
Nginx 配置:
location /protected {
internal;
alias /dir/of/protected/files/;
if_modified_since off;
output_buffers 2 1m;
open_file_cache max=50000 inactive=10m;
open_file_cache_valid 15m;
open_file_cache_min_uses 1;
open_file_cache_errors off;
}
大規模的黑客攻擊將是使用 nginx 以Range
header 將請求限制為字節范圍
像這樣的東西(未經測試,所以這可能行不通,但這個想法應該可行):
{
... snip config ...
server {
listen 80 default_server;
listen [::]:80 default_server;
root /html;
index index.html;
location / {
proxy_pass http://localhost/content;
add_header Range btyes=0,100000;
}
location /content {
try_files $uri $uri/ =404;
}
}
}
我還沒有一起測試過Slice
和X-Accel
。 如果每個文件可以具有由后端定義的不同限制,您可以在該位置配置Slice並使用X-Accel-Redirect
URL 發送限制,如下所示:
X-Accel-Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
Content-Type: application/octet-stream
Content-Length: {file_size}
Content-Disposition: attachment; filename="myfile.mp4"
Accept-Ranges: bytes
X-Accel-Buffering: yes
X-Accel-Redirect: /protected/myfile.mp4?s=0&e=$PHP_VAR
Nginx.conf
location /protected {
slice; # enable slicing
slice_start_arg s;
slice_end_arg e;
internal;
alias /dir/of/protected/files/;
if_modified_since off;
output_buffers 2 1m;
open_file_cache max=50000 inactive=10m;
open_file_cache_valid 15m;
open_file_cache_min_uses 1;
open_file_cache_errors off;
}
全局文件限制
您需要重定向包含 Slice 參數的原始請求以截斷正在提供的文件。
Nginx 配置:
location /sample {
slice; # enable slicing
slice_start_arg s;
slice_end_arg e;
internal;
alias /dir/of/protected/files/;
if_modified_since off;
output_buffers 2 1m;
open_file_cache max=50000 inactive=10m;
open_file_cache_valid 15m;
open_file_cache_min_uses 1;
open_file_cache_errors off;
}
location /protected {
rewrite ^ /sample&s=0&e=1024; # replace for the desired file limit in bytes
}
如果上面的rewrite
指令不起作用,我建議使用以下選項proxy_pass
。
location /protected {
set $file_limit 1024 # replace for the desired file limit in bytes
set $delimiter "";
if ($is_args) {
set $delimiter "&";
}
set $args $args${delimiter}s=0&e=$file_limit;
proxy_pass $scheme://127.0.0.1/sample;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.