Nginx可以很好地作为文件下载的代理服务器,以下是几种常见的配置方法:
server {
listen 80;
server_name download.example.com;
location /downloads/ {
alias /path/to/your/files/;
# 启用自动索引,可选
autoindex on;
# 设置正确的MIME类型
default_type application/octet-stream;
# 禁用缓存,确保总是获取最新文件
add_header Cache-Control "no-store, no-cache, must-revalidate";
add_header Pragma "no-cache";
}
}
如果文件存储在另一台服务器上:
server {
listen 80;
server_name download.example.com;
location /remote-files/ {
proxy_pass http://backend-fileserver/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
# 大文件下载优化
proxy_buffering off;
proxy_request_buffering off;
}
}
server {
listen 80;
server_name secure.example.com;
location /secure-downloads/ {
alias /path/to/secure/files/;
# 基本认证
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
# 限制访问IP
allow 192.168.1.0/24;
deny all;
}
}
server {
listen 80;
server_name download.example.com;
location /downloads/ {
alias /path/to/your/files/;
# 限速50KB/s
limit_rate 50k;
# 对大于10MB的文件限速
limit_rate_after 10m;
}
}
server {
listen 80;
server_name dynamic.example.com;
location /dynamic-download/ {
# 传递给后端处理
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
include fastcgi_params;
# 确保正确处理文件下载
fastcgi_param SCRIPT_FILENAME /path/to/download-script.php;
}
}
server {
listen 80;
server_name largefiles.example.com;
location /large-files/ {
alias /path/to/large/files/;
# 禁用缓冲
proxy_buffering off;
# 启用sendfile
sendfile on;
# 大文件超时设置
proxy_read_timeout 300s;
proxy_connect_timeout 75s;
}
}
client_max_body_size
指令以上配置可以根据实际需求组合使用,例如同时启用认证和限速功能。