萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Nginx 整合 ngx_upload_module 實現大檔案上傳與進度控制

ngx_upload_module 讓 Nginx 直接接收檔案上傳、暫存至磁碟,再轉發表單欄位至後端應用 (PHP、Python 等),大幅降低後端處理大檔案的壓力並支援上傳進度。本文記錄編譯安裝與配置範例。

編譯安裝步驟


mkdir ~/download && cd ~/download

# 下載模組原始碼
wget https://www.grid.net.ru/nginx/download/nginx_upload_module-2.0.12.tar.gz
tar zxf nginx_upload_module-2.0.12.tar.gz

git clone https://github.com/FRiCKLE/ngx_cache_purge.git  # 可選:快取清除模組

# 安裝建置依賴
yum groupinstall "Development Tools"
yum install pcre-devel zlib-devel openssl-devel

# 下載 Nginx 原始碼 (版本需與模組相容)
wget https://nginx.org/download/nginx-1.2.3.tar.gz
tar zxf nginx-1.2.3.tar.gz
cd nginx-1.2.3

# 配置編譯參數
./configure \
  --prefix=/usr/local/nginx \
  --with-pcre \
  --with-http_ssl_module \
  --add-module=../nginx_upload_module-2.0.12 \
  --add-module=../ngx_cache_purge

make && make install

啟動測試


/usr/local/nginx/sbin/nginx
ps aux | grep nginx

Nginx 配置範例

主站配置 mysite.conf:


server {
    listen 80;
    server_name 192.168.1.123;
    client_max_body_size 20M;

    location /upload {
        include /home/mysite/etc/nginx/ngx_upload.conf;
    }

    location @after_upload {
        proxy_pass https://www_backend;
    }
    # ... 其他 location
}

上傳模組獨立配置 ngx_upload.conf:


upload_pass @after_upload;
upload_pass_args on;
upload_cleanup 400 404 499 500-505;
upload_store /home/mysite/www/uploads/tmp;
upload_store_access user:r;
upload_limit_rate 128k;
upload_set_form_field "${upload_field_name}_name" $upload_file_name;
upload_set_form_field "${upload_field_name}_content_type" $upload_content_type;
upload_set_form_field "${upload_field_name}_path" $upload_tmp_path;
upload_aggregate_form_field "${upload_field_name}_md5" $upload_file_md5;
upload_aggregate_form_field "${upload_field_name}_size" $upload_file_size;
upload_pass_form_field "^.*$";

關鍵指令說明

指令用途
upload_pass上傳完成後轉發至的命名 location (後端處理)
upload_store暫存目錄 (需可寫)
upload_set_form_field將單一檔案屬性 (檔名、類型、路徑) 作為表單欄位傳給後端
upload_aggregate_form_field多檔案合併欄位 (如多檔 MD5、大小以逗號分隔)
upload_pass_form_field透傳原始表單所有欄位 (正則比對)
upload_cleanup指定 HTTP 狀態碼時刪除暫存檔

後端處理範例 (PHP)


// $_FILES 不會包含上傳檔案,改從 $_POST 取得模組設定的欄位
$fileName = $_POST['userfile_name'];
$filePath = $_POST['userfile_path'];
$fileMd5  = $_POST['userfile_md5'];
// 移動/處理檔案
rename($filePath, "/permanent/storage/$fileName");
注意:ngx_upload_module 開發較早,Nginx 新版本 (1.18+) 可能需修補相容性。現代專案常改用 nginx_upload_module 分支或直接在後端處理上傳 (配合 client_max_body_size、proxy_request_buffering off)。
copyright © 萬盛學電腦網 all rights reserved