1. 程式人生 > 其它 >Nginx配置檔案下載

Nginx配置檔案下載

背景:假設WEB目錄為/nginx/wwwroot,web訪問路徑為http://abc.com/,現在需要當url為http://abc.com/download/***.tar的時候,下載其他目錄下的檔案。

環境:預設vhost.conf配置如下

server {
    listen       80;
    listen       [::]:80;
    server_name  localhost;

    limit_conn perip 7;
    
    location / {
        root   /nginx/wwwroot;
        if (!-e $request_filename) {
                rewrite  ^(.*)$  /index.php?s=/$1  last;
                break;
        }
        index  index.php index.html index.htm;
    }

    error_page   500 502 503 504  /50x.html;

    location ~ \.php$ {
        root           /nginx/wwwroot;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}

方式1:反向代理(缺點:需要多開放一個埠)

server {
    listen        8099;
    root  /mnt/nandflash/;
    location / {
        autoindex on;
        autoindex_exact_size on;
        autoindex_localtime on;
        charset utf-8,gbk;
    }
}

location /download/ {
    proxy_pass http://127.0.0.1:8099/;
}

方式2 (缺點:需要通過http://abc.com/nandflash/**.zip訪問)

location ~ /nandflash  { 
    root /mnt;
    if ($request_filename ~* ^.*?\.(tar|zip)$){
        add_header Content-Disposition: 'attachment';
        add_header  Content-Type application/octet-stream;
    }
}

方式3 虛擬目錄

location ~ /download/(.*)\.(tar|zip)$ {
    alias  /mnt/nandflash/$1.$2;
}

以上3中方法,理論上應該有資料夾許可權的問題,但我環境沒碰到,本人就沒管了,算是個坑吧。

下面方式是網上很多文章中提到的辦法,但在我的環境下,沒有效果。

location ~ /download {
    alias /mnt/nandflash/;
    autoindex on;
    autoindex_exact_size on;
    autoindex_localtime on;
    charset utf-8,gbk;
}

location ~ ^/mnt/nandflash/(.*)$ {
    add_header Content-Disposition "attachment;filename=$1";
}