OpenResty를 활용한 파일 전송 서버 구축

OpenResty는 Nginx의 강력한 기능과 LuaJIT의 유연성을 결합하여 고성능 웹 애플리케이션을 구축하는 데 이상적인 플랫폼입니다. 이 가이드에서는 OpenResty를 사용하여 간단한 파일 업로드 및 다운로드 기능을 제공하는 서버를 설정하는 방법을 설명합니다.

1. 필수 Lua 모듈 설치

파일 업로드를 처리하기 위해 resty.upload 모듈이 필요합니다. opm(OpenResty Package Manager)을 사용하여 설치할 수 있습니다.

opm install ledgetech/lua-resty-upload

2. 파일 업로드 처리 Lua 스크립트 작성

OpenResty는 Nginx의 요청 처리 단계에서 Lua 스크립트를 실행할 수 있습니다. 업로드된 파일을 처리하는 Lua 스크립트를 /usr/local/openresty/nginx/lua/file_processor.lua 경로에 생성합니다.

local upload_parser = require "resty.upload"
local json_encoder = require "cjson.safe"

-- 청크 단위로 데이터를 읽기 위한 버퍼 크기 설정
local read_buffer_size = 8192
local upload_handler, handler_err = upload_parser:new(read_buffer_size)

if not upload_handler then
    ngx.log(ngx.ERR, "업로드 핸들러 생성 실패: ", handler_err)
    ngx.exit(500)
end

local stored_file_handle
local original_filename = ""
local upload_successful = false

-- URL 쿼리 파라미터에서 하위 디렉토리 경로 가져오기 (예: ?subdir=documents/reports)
local target_subdirectory = ngx.var.arg_subdir
if not target_subdirectory or target_subdirectory == "" then
    target_subdirectory = "" -- subdir 파라미터가 없으면 기본 경로 사용
end

-- 파일이 저장될 기본 디렉토리와 하위 디렉토리를 결합하여 전체 경로 생성
local base_storage_path = "/data/uploaded_files/"
local final_storage_path = base_storage_path .. target_subdirectory .. "/"

-- 필요한 경우 중첩된 디렉토리 생성
local mkdir_cmd = "mkdir -p " .. final_storage_path
os.execute(mkdir_cmd)

-- 업로드 처리 시간 제한 설정 (밀리초)
upload_handler:set_timeout(5000)

while true do
    local part_type, part_data, read_error = upload_handler:read()

    if not part_type then
        ngx.say(json_encoder.encode({ success = false, message = "데이터 읽기 실패: " .. read_error }))
        return
    end

    if part_type == "header" then
        -- Content-Disposition 헤더에서 파일명 추출
        if part_data[1] == "Content-Disposition" then
            original_filename = part_data[2]:match('filename="([^"]+)"')
            if original_filename then
                -- 파일 쓰기를 위해 파일 열기
                stored_file_handle = io.open(final_storage_path .. original_filename, "w+b") -- 바이너리 모드로 열기
                if not stored_file_handle then
                    ngx.say(json_encoder.encode({ success = false, message = "파일 생성 실패" }))
                    return
                end
            end
        end
    elseif part_type == "body" then
        -- 파일 내용 쓰기
        if stored_file_handle then
            stored_file_handle:write(part_data)
        end
    elseif part_type == "part_end" then
        -- 파일 파트 종료 시 파일 핸들 닫기
        if stored_file_handle then
            stored_file_handle:close()
            stored_file_handle = nil
            upload_successful = true
        end
    elseif part_type == "eof" then
        -- 모든 업로드 데이터가 처리되었음을 나타냄
        break
    end
end

ngx.say(json_encoder.encode({ success = upload_successful, filename = original_filename, destination_path = final_storage_path }))

3. Nginx 설정 파일 수정

OpenResty의 Nginx 설정 파일(일반적으로 /usr/local/openresty/nginx/conf/nginx.conf)을 수정하여 업로드 및 다운로드 엔드포인트를 정의합니다.

user nginx; # Nginx 워커 프로세스가 실행될 사용자 및 그룹 지정

events {
    worker_connections 1024;
}

http {
    server {
        listen 80;
        server_name localhost;

        # 파일 업로드 인터페이스
        location /upload/ {
            # Lua 스크립트를 통해 파일 업로드 요청 처리
            content_by_lua_file /usr/local/openresty/nginx/lua/file_processor.lua;
            # 클라이언트 바디 최대 크기 설정 (예: 50MB)
            client_max_body_size 50m;
        }

        # 파일 다운로드 및 디렉토리 탐색 인터페이스
        location /download/ {
            # 파일이 저장된 실제 경로 지정
            alias /data/uploaded_files/;
            # 디렉토리 목록을 웹에서 볼 수 있도록 설정
            autoindex on;
            # 파일 크기를 사람이 읽기 쉬운 형식 (MB, GB)으로 표시
            autoindex_exact_size off;
            # 파일 시간을 현지 시간으로 표시
            autoindex_localtime on;
        }
    }
}

4. 저장 디렉토리 권한 설정

Nginx 워커 프로세스가 파일을 읽고 쓸 수 있도록 파일 저장 디렉토리의 권한을 적절히 설정해야 합니다. Nginx 설정에서 지정한 사용자(예: nginx 또는 www-data)에게 쓰기 권한을 부여합니다.

sudo mkdir -p /data/uploaded_files
sudo chown -R nginx:nginx /data/uploaded_files
sudo chmod -R 755 /data/uploaded_files

Nginx 워커 프로세스의 실제 사용자 및 그룹을 확인하려면 다음 명령어를 사용할 수 있습니다.

ps -aux | grep nginx

출력에서 nginx 프로세스 옆에 표시되는 사용자 이름이 Nginx의 실행 사용자입니다. 해당 사용자로 디렉토리 소유권을 변경하거나 Nginx 설정의 user 지시어를 조정해야 합니다.

태그: OpenResty nginx Lua File Upload File Download

10월 20일 12:53에 게시됨