코샵
끄적끄적 코딩 공방
코샵

인기 글

  • 분류 전체보기 (478) N
    • MongoDB (4)
    • 일기장 (4)
    • Unity (138)
      • Tip (41)
      • Project (1)
      • Design Pattern (8)
      • Firebase (6)
      • Asset (2)
    • 파이썬 (127)
      • Basic (40)
      • OpenCV (8)
      • Pandas (15)
      • PyQT (3)
      • SBC(Single Board Computer) (1)
      • 크롤링 (14)
      • Fast API (29)
      • Package (6)
    • Linux (4)
    • C# (97)
      • Algorithm (11)
      • Window (7)
    • TypeScript (47) N
      • CSS (9) N
    • Git (11)
    • SQL (5)
    • Flutter (10)
      • Tip (1)
    • System (1)
    • BaekJoon (6)
    • Portfolio (2)
    • MacOS (1)
    • 유틸리티 (1)
    • 서비스 (6)
    • 자동화 (3)
    • Hobby (10)
      • 물생활 (10)
      • 식집사 (0)
전체 방문자
오늘
어제

최근 댓글

최근 글

반응형
hELLO · Designed By 정상우.
코샵

끄적끄적 코딩 공방

TypeScript

Nginx 413 Request Entity Too Large 오류 해결

2025. 2. 13. 12:10
반응형

** 가이드**

413 오류는 클라이언트가 업로드하는 파일이나 요청 데이터가 Nginx에서 설정된 최대 허용 크기를 초과할 때 발생합니다. 이 문제를 효과적으로 해결하는 방법을 알아보겠습니다.

오류의 주요 원인

  1. 파일 업로드 크기 제한 초과
  2. POST 요청 데이터 크기 제한 초과
  3. 클라이언트 요청 본문 버퍼 크기 제한

Nginx 설정 수정하기

http {
    # 클라이언트 요청 본문 최대 크기 설정
    client_max_body_size 100M;

    # 클라이언트 요청 본문 버퍼 크기
    client_body_buffer_size 128k;

    server {
        # 특정 위치에 대한 설정
        location /upload {
            # 이 위치에 대한 특별한 크기 제한
            client_max_body_size 200M;
        }
    }
}

FastAPI와 함께 사용하는 경우

from fastapi import FastAPI, UploadFile
from fastapi.responses import JSONResponse

app = FastAPI()

@app.post("/upload/")
async def create_upload_file(file: UploadFile):
    try:
        contents = await file.read()
        # 파일 처리 로직
        return {"filename": file.filename}
    except Exception as e:
        return JSONResponse(
            status_code=413,
            content={"message": "File too large"}
        )

단계별 해결 방법

  1. nginx.conf 파일 위치 확인

    # nginx.conf 위치 찾기
    nginx -t
  2. 설정 변경 및 적용

    # 설정 파일 편집
    sudo nano /etc/nginx/nginx.conf
    

설정 문법 검사

sudo nginx -t

Nginx 재시작

sudo systemctl restart nginx


3. **로그 확인**
```bash
# 에러 로그 확인
tail -f /var/log/nginx/error.log

고급 설정 예시

http {
    # 기본 설정
    client_max_body_size 10M;

    # 프록시 설정
    proxy_connect_timeout 600;
    proxy_send_timeout 600;
    proxy_read_timeout 600;
    send_timeout 600;

    # 특정 서버 블록
    server {
        # API 엔드포인트용 대용량 설정
        location /api/upload {
            client_max_body_size 500M;
            proxy_pass http://backend;

            # 버퍼 설정
            proxy_buffer_size 128k;
            proxy_buffers 4 256k;
            proxy_busy_buffers_size 256k;
        }

        # 일반 업로드용 설정
        location /upload {
            client_max_body_size 100M;
            proxy_pass http://backend;
        }
    }
}

주의사항

  1. 메모리 사용량 고려

    • 너무 큰 client_max_body_size 설정은 서버 메모리 부족 초래 가능
    • 적절한 버퍼 크기 설정 필요
  2. 보안 고려사항

    • 무제한 업로드는 DDoS 공격 위험
    • 파일 형식별 제한 설정 권장
  3. 백엔드 설정과의 조화

    # FastAPI 설정 예시
    from fastapi import FastAPI, File, UploadFile
    import shutil
    

app = FastAPI()

@app.post("/upload/")
async def create_upload_file(file: UploadFile = File(...)):
try:
# 임시 파일로 저장
with open(f"temp/{file.filename}", "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
return {"filename": file.filename}
except Exception as e:
return {"error": str(e)}


### **모니터링 및 로깅 설정**
```nginx
http {
    # 로깅 설정
    log_format upload '$remote_addr - $remote_user [$time_local] '
                     '"$request" $status $body_bytes_sent '
                     '"$http_referer" "$http_user_agent" '
                     '$request_body_file';

    server {
        location /upload {
            access_log /var/log/nginx/upload.log upload;
            error_log /var/log/nginx/upload-error.log;
        }
    }
}

이러한 설정들을 통해 413 오류를 효과적으로 해결하고 대용량 파일 업로드를 안정적으로 처리할 수 있습니다. 서버의 리소스와 사용 사례에 맞게 적절한 값을 설정하는 것이 중요합니다.

저작자표시 비영리 변경금지 (새창열림)

'TypeScript' 카테고리의 다른 글

React : map  (0) 2025.02.16
React useEffect 의존성 경고  (1) 2025.02.14
Enum을 넘어서 - const assertions의 장점과 Tree-shaking  (0) 2025.02.12
[REST API] RESTful API 설계 가이드  (1) 2025.01.29
[HTTP Header 다루기] fetch API의 Headers 인터페이스  (0) 2025.01.26
    'TypeScript' 카테고리의 다른 글
    • React : map
    • React useEffect 의존성 경고
    • Enum을 넘어서 - const assertions의 장점과 Tree-shaking
    • [REST API] RESTful API 설계 가이드
    코샵
    코샵
    나의 코딩 일기장

    티스토리툴바