클라우드 기본 Nginx 세팅 - 100-hours-a-week/16-Hot6-wiki GitHub Wiki

클라우드 기본 Nginx 세팅

이 문서는 nginx.confsites-available/default 설정을 기준으로 Spring Backend와 FastAPI AI 서버를 보호하고 운영하기 위한 Nginx 구성을 설명합니다.

nginx.conf

limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=5r/s;
limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
  • $binary_remote_addr: 클라이언트 IP 주소를 바이트 단위로 표현하여 고정된 크기의 키 사용 가능
  • zone=...:10m: 10MB 공유 메모리를 zone으로 할당 (수천~수만 IP 저장 가능)
  • rate=5r/s: 초당 5건 요청 허용
  • limit_conn_zone: IP별 동시 연결 수 제한 설정

이 설정은 http {} 블럭 안에 위치해야 하며, 실제 제한 적용은 각 server 블럭에서 수행합니다.

HTTP → HTTPS 리다이렉트

server {
    listen 80;
    server_name backend.onthe-top.com;

    location /.well-known/acme-challenge/ {
        root /var/www/html;
    }

    location / {
        return 301 https://$host$request_uri;
    }
}
  • HTTP 요청은 모두 HTTPS로 리다이렉션
  • 단, 인증서 발급용 .well-known 경로는 예외 처리 필요

SSL 인증서 설정

ssl_certificate     /etc/letsencrypt/live/backend.onthe-top.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/backend.onthe-top.com/privkey.pem;
include             /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam         /etc/letsencrypt/ssl-dhparams.pem;
  • Certbot을 통해 발급된 Let's Encrypt 인증서를 사용
  • 강력한 DH 파라미터와 SSL 옵션 포함

민감한 파일 차단 + 요청 제한

client_max_body_size 30M;

limit_req zone=req_limit_per_ip burst=10 nodelay;
limit_conn conn_limit_per_ip 5;

location / {
    if ($request_uri ~* "\.(git|env|sql|bak)$") {
        return 403;
    }

    proxy_pass http://localhost:8080/;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_http_version 1.1;
    proxy_cache_bypass $http_upgrade;
}
  • client_max_body_size: 최대 30MB 업로드 허용
  • limit_req: 초당 5건 요청, burst=10까지는 대기 없이 통과
  • limit_conn: 동시 연결 5개까지 허용
  • 민감한 확장자 요청은 403 Forbidden 처리

Virtual Host: Spring Backend

server {
    listen 443 ssl;
    server_name backend.onthe-top.com;

    ssl_certificate     /etc/letsencrypt/live/backend.onthe-top.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/backend.onthe-top.com/privkey.pem;
    include             /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam         /etc/letsencrypt/ssl-dhparams.pem;

    client_max_body_size 30M;
    limit_req zone=req_limit_per_ip burst=10 nodelay;
    limit_conn conn_limit_per_ip 5;

    location / {
        if ($request_uri ~* "\.(git|env|sql|bak)$") {
            return 403;
        }

        proxy_pass http://localhost:8080/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_http_version 1.1;
        proxy_cache_bypass $http_upgrade;
    }
}

요약

항목 설정 요약
HTTP 리디렉션 모든 HTTP 요청 → HTTPS 리다이렉션
인증서 적용 Let's Encrypt 인증서 (/etc/letsencrypt/...)
파일 크기 제한 client_max_body_size 30M
요청 속도 제한 limit_req + burst=10 + nodelay
연결 수 제한 limit_conn
민감 파일 차단 .git, .env, .sql, .bak → 403
서비스 프록시 Spring: localhost:8080