插件窝 干货文章 nginx代理下载服务器文件的方法

nginx代理下载服务器文件的方法

server 文件下载 Nginx 限速 731    来源:    2025-04-22

Nginx代理下载服务器文件的方法

Nginx可以很好地作为文件下载的代理服务器,以下是几种常见的配置方法:

1. 基本文件下载代理配置

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";
    }
}

2. 代理到后端文件服务器

如果文件存储在另一台服务器上:

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;
    }
}

3. 带认证的文件下载

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;
    }
}

4. 限速下载

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;
    }
}

5. 动态文件下载(通过PHP等后端)

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;
    }
}

6. 大文件下载优化

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;
    }
}

注意事项

  1. 确保文件目录有正确的权限,Nginx用户(通常是www-data或nginx)需要有读取权限
  2. 对于大文件下载,考虑调整client_max_body_size指令
  3. 生产环境建议使用HTTPS加密下载
  4. 监控下载流量,防止滥用

以上配置可以根据实际需求组合使用,例如同时启用认证和限速功能。