Skip to content

Nginx 치트시트

고성능 HTTP 서버이자 리버스 프록시입니다.

01

시작하기

기본 설정

Nginx 설정은 계층적 블록 구조를 씁니다. worker_processes가 프로세스 수를 정합니다. http 블록이 server 블록을 담고, server 블록이 location 블록을 담습니다. 리로드 전에는 항상 nginx -t로 테스트하세요.

nginx
# /etc/nginx/nginx.conf
worker_processes auto;

events {
    worker_connections 1024;
}

http {
    server {
        listen 80;
        server_name example.com;

        location / {
            root /var/www/html;
            index index.html;
        }
    }
}

# Test config: nginx -t
# Reload: nginx -s reload
# Start: systemctl start nginx

디렉티브와 컨텍스트

컨텍스트는 중첩됩니다. main > events/http/mail > server > location. 단순 디렉티브는 세미콜론으로 끝나고 블록 디렉티브는 중괄호를 씁니다. 일부 디렉티브는 특정 컨텍스트에서만 유효합니다.

nginx
# Contexts are hierarchical blocks
# Global context (main) - outside any block
user nginx;
worker_processes auto;

# events context
events {
    worker_connections 1024;
}

# http context
http {
    # server context
    server {
        listen 80;
        # location context
        location / {
            root /var/www/html;
        }
    }
}

# Directives: simple (name value;) or block (name { ... })

테스트와 리로드

nginx -t는 문법을 검사하고 참조된 파일(인증서, 로그)을 열려고 합니다. 리로드 전에 항상 실행하세요. reload는 SIGHUP을 보내며, 워커는 현재 요청을 마친 뒤 재적재합니다. restart는 잠깐의 다운타임을 일으킵니다.

nginx
# test configuration for syntax errors
nginx -t

# test and print full config
nginx -T

# reload config without dropping connections
nginx -s reload

# stop gracefully (finishes current requests)
nginx -s quit

# stop immediately
nginx -s stop

# reopen log files (after log rotation)
nginx -s reopen

# systemd alternative
systemctl reload nginx
systemctl restart nginx

Main vs HTTP 컨텍스트

worker_processes와 events는 main 컨텍스트에 있습니다. 라우팅, 프록시, 캐싱, server 블록은 http에 있습니다. SSL, 로깅, gzip은 http에서 설정해 server/location이 상속할 수 있습니다.

nginx
# main context - global settings
user nginx;
worker_processes auto;
worker_rlimit_nofile 65535;
pid /var/run/nginx.pid;

events {
    worker_connections 4096;
}

http {
    # all HTTP-related config lives here
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    sendfile      on;
    keepalive_timeout 65;

    include /etc/nginx/conf.d/*.conf;
}

Include 파일

include가 설정을 모듈화합니다. conf.d 글롭(*.conf)이 현대적 관례이고, 심링크를 쓰는 sites-enabled는 Debian/Ubuntu 패턴입니다. mime.types가 파일 확장자를 Content-Type으로 매핑합니다.

nginx
# main config: /etc/nginx/nginx.conf
http {
    include /etc/nginx/mime.types;
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

# /etc/nginx/conf.d/default.conf
server {
    listen 80;
    server_name example.com;
    root /var/www/html;
}

# Disable a site: remove the file from sites-enabled/
# Available sites kept in sites-available/, symlinked into enabled/

명령줄 연산

nginx -V는 내장 모듈을 포함한 컴파일 옵션을 보여 줍니다. -g는 설정을 무시하는 디렉티브를 정하고, -c는 기본 설정을 건드리지 않고 다른 설정을 테스트할 때 유용합니다.

nginx
# start nginx (if not managed by systemd)
nginx

# specify a custom config file
nginx -c /path/to/nginx.conf

# set a global directive from command line
nginx -g "worker_processes 4;"

# test config
nginx -t

# print version and build configuration
nginx -V

# send signal to master process
nginx -s reload
nginx -s stop
02

Server 블록

기본 Server 블록

server 블록은 가상 호스트를 정의합니다. listen이 포트를 정하고, server_name이 Host 헤더를 매칭하며, root가 문서 루트를 정하고, index가 디렉터리 요청에 제공할 파일을 지정합니다.

nginx
server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/example;
    index index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }
}

여러 Server Name

Nginx는 server_name을 정확 매칭, 그다음 와일드카드(*.foo.com), 그다음 정규식 순으로 매칭합니다. 첫 매칭 server 블록이 요청을 처리합니다. 같은 포트의 다른 앱에는 별도 블록을 쓰세요.

nginx
server {
    listen 80;
    server_name example.com www.example.com;
    # ...
}

server {
    listen 80;
    server_name api.example.com;
    # ...
}

# Wildcard: matches any single-level subdomain
server_name *.example.com;

# Regex (starts with ~)
server_name ~^www\d+\.example\.com$;

Default Server

default_server가 server_name과 매칭되지 않는 Host 헤더의 요청을 처리합니다. 밑줄(_)은 관례입니다(유효하지 않은 호스트명이므로 실제 트래픽과 매칭되지 않음). return 444는 응답 없이 연결을 닫습니다.

nginx
# mark a server block as default for the port
server {
    listen 80 default_server;
    server_name _;
    return 444;  # drop connection (no response)
}

# handles all requests that don't match another server_name
# _ is an invalid hostname, used as catch-all convention
# useful to block requests with no matching Host header

Listen 디렉티브

listen은 특정 주소, IPv6, UNIX 소켓에 바인딩하거나 default_server를 설정할 수 있습니다. ssl 파라미터가 해당 리스너의 TLS를 켭니다. 한 server 블록에 여러 listen 디렉티브가 허용됩니다.

nginx
# listen on port 80
listen 80;

# IPv6
listen [::]:80;

# HTTPS (ssl flag)
listen 443 ssl;
listen [::]:443 ssl;

# specific address
listen 127.0.0.1:8080;

# default server for this port
listen 80 default_server;

# listen on UNIX socket
listen unix:/var/run/nginx.sock;

Server Name 매칭

매칭 우선순위는 정확 > 선행 와일드카드 > 후행 와일드카드 > 정규식입니다. 정규식은 설정 순서대로 검사되므로 첫 매칭이 이깁니다. server_name이 길거나 많으면 해시 버킷 크기를 늘리세요.

nginx
# Order of precedence (highest to lowest):
# 1. Exact name: example.com
# 2. Longest wildcard starting with *: *.example.com
# 3. Longest wildcard ending with *: www.*
# 4. First matching regex (in config order): ~^www\d+\.

# If nothing matches, the default_server handles it

# Tune hash sizes for many server names
http {
    server_names_hash_bucket_size 64;
    server_names_hash_max_size 512;
}

Catch-all Server

catch-all은 임의 Host 헤더의 요청이 앱에 도달하지 못하게 막습니다. return 301은 알려진 호스트로 리다이렉트하고, return 444는 연결을 끊어 IP를 직접 치는 스캐너에 유용합니다.

nginx
# catch all requests regardless of host header
server {
    listen 80 default_server;
    server_name _;  # invalid name, never matches real host

    return 301 https://$host$request_uri;
}

# or drop the connection silently
server {
    listen 80 default_server;
    server_name _;
    return 444;
}

# redirect unknown subdomains to main site
server {
    listen 80 default_server;
    return 301 https://example.com;
}
03

Location 블록

Location 수식어

수식어가 매칭 동작을 바꿉니다. = (정확), ^~ (접두어, 정규식 생략), ~ (대소문자 구분 정규식), ~* (대소문자 무시 정규식), 없음(접두어). 정규식은 파일 확장자에, 접두어는 경로 트리에 적합합니다.

nginx
# exact match - fastest, stops search if matched
location = /favicon.ico {
    log_not_found off;
}

# prefix match with ^~ - skips regex if longest prefix matches
location ^~ /static/ {
    root /var/www;
}

# case-sensitive regex
location ~ \.php$ {
    fastcgi_pass unix:/run/php/php-fpm.sock;
}

# case-insensitive regex
location ~* \.(jpg|jpeg|png|gif|ico)$ {
    expires 30d;
}

# prefix match (no modifier)
location / {
    try_files $uri $uri/ /index.php;
}

Location 우선순위

Nginx는 정확 매칭(=)을 먼저, 그다음 접두어 매칭(가장 긴 것이 이김), 그다음 설정 순서대로 정규식을 평가합니다. ^~는 접두어 매칭이 정규식 평가를 건너뛰게 합니다. 이 순서를 이해하면 겹치는 location의 놀라움을 피합니다.

nginx
# Priority order (highest to lowest):
# 1. =     exact match
# 2. ^~    prefix match (skips regex if matched)
# 3. ~ ~*  regex (first match in config order)
# 4. (none) prefix match (longest wins)

location = /api {
    # exact, highest priority
}

location ^~ /assets/ {
    # prefix, beats regex
}

location ~ \.php$ {
    # regex
}

location /api/ {
    # prefix, lowest of these
}

Root vs Alias

root는 URI를 자신의 값에 덧붙이고, alias는 매칭된 접두어를 교체합니다. location이 트리의 하위 디렉터리에 대응하면 root, URI 경로와 파일시스템 경로가 다르면 alias를 쓰세요. 정규식과 함께 쓰는 alias에는 $1 캡처가 필요합니다.

nginx
# root: appends the full URI to the path
# request /img/cat.png -> /var/www/img/cat.png
location /img/ {
    root /var/www;
}

# alias: replaces the matched location part
# request /img/cat.png -> /data/images/cat.png
location /img/ {
    alias /data/images/;
}

# alias with regex requires capturing the path
location ~ ^/img/(.*)$ {
    alias /data/images/$1;
}

try_files

try_files는 각 인자를 순서대로 검사하며 마지막은 폴백입니다(파일 검사 없음). $uri는 파일을, $uri/는 디렉터리를 검사합니다. 폴백은 URI, =code, @named가 될 수 있습니다. SPA와 CMS 라우팅에 필수입니다.

nginx
# try files in order, fall back to last option
location / {
    try_files $uri $uri/ /index.html;
}

# serve index.php if file/dir not found (pretty URLs)
location / {
    try_files $uri $uri/ /index.php?$query_string;
}

# return 404 if nothing matches
location / {
    try_files $uri =404;
}

# named location as fallback
location / {
    try_files $uri $uri/ @drupal;
}

Named Location

named location(@name)은 내부 전용이며 요청 URI로 직접 매칭되지 않습니다. try_files, error_page, rewrite의 대상입니다. 폴백 핸들러 같은 설정 블록을 여러 location에서 공유하기 좋습니다.

nginx
# named locations start with @, can't be reached externally
# used as try_files fallback or rewrite target

location / {
    try_files $uri $uri/ @app;
}

location @app {
    fastcgi_pass unix:/run/php.sock;
    # ... fastcgi config
}

# useful for organizing common error logic
location @error_page {
    return 500 "Internal Server Error";
}

# can also be used with error_page
error_page 404 @fallback;
location @fallback {
    proxy_pass http://backend;
}

중첩 Location

location은 중첩할 수 있습니다. 안쪽 location은 바깥 것을 상속하고 재정의할 수 있습니다. 넓은 접두어 안에서 특정 경로를 특별 처리할 때 유용합니다(예: 업로드용 더 큰 바디 크기, 특정 하위 경로의 정적 파일 제공).

nginx
location /api {
    # /api/users, /api/posts handled here
    proxy_pass http://backend;

    location /api/upload {
        # override for upload endpoint
        client_max_body_size 50M;
        proxy_pass http://upload_backend;
    }

    location ~ ^/api/static/(.*)$ {
        # regex inside prefix location
        root /var/www;
    }
}
04

리버스 프록시

기본 Proxy Pass

proxy_pass는 요청을 업스트림 서버로 전달합니다. proxy_pass의 후행 슬래시는 매칭된 location 접두어를 교체하게 하고, 후행 슬래시가 없으면 원래 URI가 그대로 전달됩니다.

nginx
server {
    listen 80;
    server_name app.example.com;

    location / {
        proxy_pass http://localhost:3000;
    }
}

# proxy_pass with URI replacement (trailing slash matters)
location /api/ {
    proxy_pass http://backend/;  # /api/foo -> /foo
}

# without trailing slash, URI is preserved
location /api/ {
    proxy_pass http://backend;   # /api/foo -> /api/foo
}

Proxy 헤더

기본적으로 nginx는 클라이언트 IP나 원래 호스트를 전달하지 않습니다. X-Real-IP와 X-Forwarded-For를 설정하면 백엔드가 실제 클라이언트를 식별할 수 있습니다. X-Forwarded-Proto는 원래 스킴을 알려 주며 HTTPS 리다이렉트 로직에 중요합니다.

nginx
location / {
    proxy_pass http://backend;

    # preserve original host
    proxy_set_header Host $host;

    # real client IP (not nginx's)
    proxy_set_header X-Real-IP $remote_addr;

    # forwarded-for chain
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    # scheme (http or https)
    proxy_set_header X-Forwarded-Proto $scheme;

    # original host
    proxy_set_header X-Forwarded-Host $host;
}

Upstream Proxy

upstream 블록은 proxy_pass가 참조할 수 있는 이름 붙은 서버 풀을 정의합니다. 이로써 로드 밸런싱, 헬스 체크, keepalive 연결이 가능해집니다. upstream 변수는 어떤 백엔드가 각 요청을 처리했는지 로깅에 유용합니다.

nginx
# define a named pool of backend servers
upstream backend {
    server 10.0.0.1:8080;
    server 10.0.0.2:8080;
    server 10.0.0.3:8080;
}

server {
    listen 80;

    location / {
        proxy_pass http://backend;
    }
}

# useful upstream variables:
# $upstream_addr, $upstream_status,
# $upstream_response_time, $upstream_cache_status

Proxy 타임아웃

proxy_connect_timeout은 TCP 핸드셰이크 한도이고, read/send 타임아웃은 데이터 전송 중 유휴 구간에 적용됩니다. 느린 엔드포인트(내보내기, AI 추론)에는 read_timeout을 늘리세요. upstream keepalive가 연결을 재사용해 지연을 줄입니다.

nginx
location / {
    proxy_pass http://backend;

    # connect timeout (TCP handshake to upstream)
    proxy_connect_timeout 5s;

    # time between reads from upstream (response)
    proxy_read_timeout 60s;

    # time between writes to upstream (request body)
    proxy_send_timeout 60s;

    # for slow backends (large uploads/downloads)
    proxy_read_timeout 300s;
}

# keepalive connections to upstream
upstream backend {
    server 10.0.0.1:8080;
    keepalive 32;
}

Proxy 버퍼링

버퍼링은 업스트림 응답을 클라이언트에 보내기 전 메모리/디스크에 저장합니다. 느린 클라이언트에는 효율적이지만 스트리밍을 깨뜨립니다. SSE, WebSocket, 청크 스트리밍에는 끄세요. buffer_size는 첫 부분(헤더)이고 buffers가 나머지를 담습니다.

nginx
location / {
    proxy_pass http://backend;

    # enable buffering (default on)
    proxy_buffering on;
    proxy_buffer_size 4k;
    proxy_buffers 8 4k;

    # busy buffers during streaming
    proxy_busy_buffers_size 16k;

    # disable for streaming/SSE
    proxy_buffering off;
    proxy_cache off;
}

# Server-Sent Events or streaming responses
location /events {
    proxy_pass http://backend;
    proxy_buffering off;
    proxy_cache off;
    chunked_transfer_encoding on;
}

WebSocket Upgrade

WebSocket은 HTTP/1.1과 Upgrade, Connection 헤더가 필요합니다. map 블록이 Upgrade 헤더를 올바른 Connection 값(upgrade vs close)으로 변환합니다. 긴 proxy_read_timeout이 유휴 WebSocket이 닫히는 것을 막습니다.

nginx
# Map the Upgrade header to a Connection value
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 80;

    location /ws {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;

        # keepalive for long-lived connections
        proxy_read_timeout 3600s;
    }
}
05

로드 밸런싱

Upstream 블록

upstream 블록이 백엔드 서버를 정의합니다. 기본 로드 밸런싱은 round-robin입니다. max_fails와 fail_timeout이 수동 헬스 체크를 구성합니다. fail_timeout 안에서 max_fails회 실패하면 그 서버는 fail_timeout초 동안 다운 표시됩니다.

nginx
upstream backend {
    server backend1.example.com weight=5;
    server backend2.example.com;
    server backend3.example.com max_fails=3 fail_timeout=30s;
}

server {
    location / {
        proxy_pass http://backend;
    }
}

# default algorithm: round-robin
# max_fails: failed attempts before marking server down
# fail_timeout: window for counting fails AND downtime duration

로드 밸런싱 방식

round-robin은 균등 분배, least_conn은 가장 한가로운 서버로, ip_hash는 같은 클라이언트를 같은 서버에(IP 기반 스티키 세션), hash는 커스텀 키로 분배합니다. consistent 파라미터는 서버 추가/제거 시 재배분을 최소화합니다.

nginx
# round-robin (default) - even distribution
upstream backend {
    server s1.example.com;
    server s2.example.com;
}

# least connections - fewest active connections
upstream backend {
    least_conn;
    server s1.example.com;
    server s2.example.com;
}

# ip_hash - sticky by client IP (session persistence)
upstream backend {
    ip_hash;
    server s1.example.com;
    server s2.example.com;
}

# generic hash (key-based, e.g., by URI or header)
upstream backend {
    hash $request_uri consistent;
    server s1.example.com;
    server s2.example.com;
}

가중 Round Robin

weight가 트래픽 분배를 비례적으로 제어합니다. 기본 weight는 1입니다. 더 강한 서버에 더 높은 weight를 줘 더 큰 몫을 맡기세요. weight는 round-robin, least_conn, ip_hash와 함께 동작합니다.

nginx
upstream backend {
    server s1.example.com weight=3;  # 3x traffic
    server s2.example.com weight=2;  # 2x traffic
    server s3.example.com weight=1;  # 1x traffic (default)
}

# total weight = 6
# s1 gets 3/6 = 50%, s2 gets 2/6 = 33%, s3 gets 1/6 = 17%

# useful when servers have different capacity
# e.g., a 4-core server gets weight=4, a 2-core gets weight=2

헬스 체크

오픈소스 nginx는 실제 요청 실패 기반의 수동 헬스 체크(max_fails/fail_timeout)를 씁니다. NGINX Plus는 URI를 주기적으로 폴링하는 능동 헬스 체크를 더합니다. 서버는 'passes'회 연속 통과해야 다시 정상 표시됩니다.

nginx
upstream backend {
    server s1.example.com max_fails=3 fail_timeout=30s;
    server s2.example.com max_fails=3 fail_timeout=30s;

    # passive health check (default behavior):
    # 3 failures within 30s marks the server down
    # it stays down for fail_timeout (30s) before retry
}

# NGINX Plus active health check
upstream backend {
    server s1.example.com;
    server s2.example.com;
    health_check interval=10s fails=3 passes=2;
    health_check uri=/health;
}

세션 지속성

ip_hash는 클라이언트 IP로 스티키 세션을 제공하지만 IP가 바뀌면(모바일 네트워크) 깨집니다. consistent를 준 hash 디렉티브는 풀 변화 시 키 재배분을 최소화합니다. sticky cookie(Plus)는 클라이언트를 서버에 고정하는 쿠키를 설정합니다.

nginx
# ip_hash: routes by client IP (uses first 3 IPv4 octets)
upstream backend {
    ip_hash;
    server s1.example.com:8080;
    server s2.example.com:8080;
}

# sticky cookie (NGINX Plus only)
upstream backend {
    sticky cookie srv_id expires=1h domain=.example.com path=/;
    server s1.example.com;
    server s2.example.com;
}

# hash with consistent parameter for minimal redistribution
upstream backend {
    hash $http_x_session_id consistent;
    server s1.example.com;
    server s2.example.com;
}

백업 서버

backup 파라미터로 표시된 서버는 모든 프라이머리가 실패할 때만 트래픽을 받습니다. 흔한 패턴: 프라이머리가 앱을 제공하고, 백업은 정적 유지보수 페이지를 제공합니다. 백업 서버는 정상 로드 밸런싱에서 제외됩니다.

nginx
upstream backend {
    server s1.example.com;
    server s2.example.com;

    # used only when all primaries are down
    server s3.example.com backup;
    server s4.example.com backup;
}

# backup servers receive traffic ONLY when all
# non-backup servers are unavailable
# useful for a maintenance page or DR fallback

upstream backend {
    server primary.example.com;
    server standby.example.com backup;
}
06

SSL/TLS 설정

기본 HTTPS 서버

listen의 ssl 파라미터가 TLS를 켭니다. ssl_certificate는 인증서 체인(서버 인증서 + 중간 인증서)을, ssl_certificate_key는 개인 키를 가리킵니다. 클라이언트가 체인을 검증할 수 있도록 항상 fullchain.pem을 쓰세요.

nginx
server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate     /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;

    root /var/www/html;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

SSL 인증서 구성

Let's Encrypt는 /etc/letsencrypt/live/<domain>/ 아래에 인증서를 둡니다. fullchain.pem은 중간 인증서를 포함하고, privkey.pem은 개인 키입니다. nginx는 서버별로 여러 인증서 타입을 지원하며 클라이언트 능력에 따라 선택합니다.

nginx
# Let's Encrypt paths
ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

# multiple cert types (RSA + ECDSA) on one server
server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate     /etc/ssl/example.com.rsa.crt;
    ssl_certificate_key /etc/ssl/example.com.rsa.key;

    ssl_certificate     /etc/ssl/example.com.ecdsa.crt;
    ssl_certificate_key /etc/ssl/example.com.ecdsa.key;
}

HTTP → HTTPS 리다이렉트

가장 깔끔한 패턴은 리다이렉트만 하는 전용 80포트 서버입니다. $host가 원래 호스트명을 유지합니다. 결합된 블록에서 if ($scheme)도 동작하지만 별도 서버 방식이 권장되며 'if is evil' 함정을 피합니다.

nginx
# redirect all HTTP traffic to HTTPS
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}

# single server block handling both
server {
    listen 80;
    listen 443 ssl;
    server_name example.com;

    ssl_certificate     /etc/ssl/example.com.crt;
    ssl_certificate_key /etc/ssl/example.com.key;

    if ($scheme != "https") {
        return 301 https://$host$request_uri;
    }
}

SSL 프로토콜과 암호 스위트

오래된 프로토콜(SSLv3, TLSv1.0/1.1)은 비활성화하세요. TLS 1.3이 가장 빠르고 안전합니다. 테스트된 프로파일은 Mozilla SSL Configuration Generator를 쓰세요. shared:SSL 캐시가 워커 간 세션 재개를 빠르게 합니다.

nginx
server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate     /etc/ssl/example.com.crt;
    ssl_certificate_key /etc/ssl/example.com.key;

    # modern configuration (Mozilla SSL Config Generator)
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers off;

    # session settings
    ssl_session_tickets off;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
}

HSTS

HSTS는 브라우저에게 도메인에 항상 HTTPS를 쓰라고 알려 SSL-stripping 공격을 막습니다. max-age는 초 단위이며(31536000 = 1년), includeSubDomains는 모든 서브도메인을 커버합니다. preload는 사이트를 브라우저 내장 목록에 제출하며 사실상 되돌릴 수 없으니 신중히 쓰세요.

nginx
server {
    listen 443 ssl;
    server_name example.com;

    # HSTS: force HTTPS for 1 year (include subdomains)
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    # preload list (be very careful — requires permanent HTTPS)
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
}

# Preload commits your domain to a browser-baked HTTPS-only list.
# Only enable preload after verifying all subdomains work on HTTPS.

OCSP Stapling

OCSP stapling은 nginx가 인증서의 폐기 상태를 가져와 제공하게 해 클라이언트의 OCSP 응답자 왕복을 줄입니다. OCSP 응답 검증에는 ssl_trusted_certificate가 필요하고, nginx가 OCSP 서버에 도달하려면 resolver가 필요합니다.

nginx
server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate     /etc/ssl/example.com/fullchain.pem;
    ssl_certificate_key /etc/ssl/example.com/privkey.pem;

    ssl_stapling on;
    ssl_stapling_verify on;

    # trust chain for verification
    ssl_trusted_certificate /etc/ssl/example.com/chain.pem;

    # DNS resolver needed for OCSP requests
    resolver 8.8.8.8 8.8.4.4 valid=300s;
    resolver_timeout 5s;
}
07

정적 파일 제공

정적 파일 제공

root가 문서 루트를 정의하며 nginx는 요청 URI를 파일 경로로 매핑합니다. try_files가 파일을 검사하고, 디렉터리를 검사한 뒤 404를 반환합니다. server 수준의 root는 모든 location이 상속하며 location별 재정의도 가능합니다.

nginx
server {
    listen 80;
    server_name example.com;
    root /var/www/html;

    location / {
        try_files $uri $uri/ =404;
    }
}

# root set at server level is inherited by all locations
# request /images/logo.png -> /var/www/html/images/logo.png
# request /css/style.css   -> /var/www/html/css/style.css

Index 디렉티브

index는 디렉터리 요청 시 시도할 파일을 나열합니다. 존재하는 첫 파일이 제공됩니다. 모두 없고 autoindex가 꺼져 있으면 nginx는 403을 반환합니다. 순서가 중요하니 선호 파일을 먼저 두세요.

nginx
server {
    listen 80;
    root /var/www/html;

    # try these files in order when request targets a directory
    index index.html index.htm index.php;

    location / {
        try_files $uri $uri/ =404;
    }
}

# request / -> tries /var/www/html/index.html, then index.htm
# request /about/ -> tries /var/www/html/about/index.html
# if no index file found and autoindex off -> 403 Forbidden

SPA를 위한 try_files

SPA는 클라이언트 측 라우팅을 쓰므로 알 수 없는 경로는 index.html을 제공해야 합니다. try_files $uri $uri/ /index.html이 정확히 그 일을 합니다. 해시된 에셋은 immutable로 1년 캐시하세요. 내용 기반 파일명이 내용 변화 시 새 URL을 보장합니다.

nginx
# Single Page Application (React, Vue, Angular)
server {
    listen 80;
    root /var/www/spa;

    location / {
        # serve static files, fall back to index.html for client routing
        try_files $uri $uri/ /index.html;
    }

    # cache static assets aggressively (filename usually hashed)
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}

Autoindex (디렉터리 목록)

autoindex는 HTML 디렉터리 목록을 생성합니다. 파일 다운로드 사이트에 유용합니다. 가독성을 위해 exact_size를 끄고, 올바른 타임스탬프를 위해 localtime을 켜세요. 민감한 파일이 있는 디렉터리에서는 절대 켜지 마시고 항상 접근 제어와 함께 쓰세요.

nginx
location /files/ {
    autoindex on;
    autoindex_exact_size off;  # human-readable sizes (KB, MB)
    autoindex_localtime on;    # show local time instead of UTC
    root /var/www;
}

# /files/        -> directory listing
# /files/doc.pdf -> downloads the file
# /files/sub/    -> listing of subdirectory

# disable for security on sensitive directories
location /private/ {
    autoindex off;
    deny all;
}

Expire 헤더

expires가 Cache-Control max-age를 설정합니다. immutable은 파일이 절대 바뀌지 않는다고 브라우저에 알려 재검증을 건너뜁니다. 해시된 에셋(file.abc123.js)에는 1y + immutable이 이상적입니다. HTML은 사용자가 즉시 갱신을 받도록 항상 재검증해야 합니다.

nginx
# cache static assets for a year
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
    access_log off;
}

# never cache HTML (always revalidate)
location ~* \.html$ {
    add_header Cache-Control "no-cache, no-store, must-revalidate";
}

# short cache for API responses
location /api/ {
    add_header Cache-Control "no-cache";
}

정적 로깅 비활성화

정적 에셋과 favicon/robots 요청은 액세스 로그를 어지럽힙니다. access_log off가 로깅을 멈추고, log_not_found off가 404 로그 항목을 억제합니다. 로그가 의미 있는 트래픽에 집중되고 바쁜 사이트의 디스크 I/O가 줄어듭니다.

nginx
# don't log requests for static assets
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
    access_log off;
    log_not_found off;
    expires 1y;
}

# don't log favicon requests (often 404 from browsers)
location = /favicon.ico {
    log_not_found off;
    access_log off;
}

# don't log robots.txt
location = /robots.txt {
    log_not_found off;
    access_log off;
}
08

Gzip 압축

Gzip 활성화

gzip이 응답을 압축해 대역폭을 줄입니다. gzip_vary는 캐시를 위해 'Vary: Accept-Encoding'을 추가하고, gzip_proxied any는 프록시된 요청도 압축합니다. comp_level 6은 CPU와 크기의 균형입니다. min_length 256은 오버헤드가 이득을 초과하는 작은 응답을 건너뜁니다.

nginx
http {
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_min_length 256;
    gzip_types
        text/plain
        text/css
        text/xml
        application/json
        application/javascript
        application/xml+rss
        application/atom+xml
        image/svg+xml;
}

Gzip 타입

gzip_types가 압축할 MIME 타입을 나열합니다. text/html은 기본으로 항상 압축됩니다. 이미 압축된 바이너리 형식(이미지, 비디오, 아카이브)은 압축하지 마세요. 크기 감소 없이 CPU만 낭비하고 출력이 커질 수도 있습니다.

nginx
http {
    gzip on;
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/javascript
        application/x-javascript
        application/json
        application/xml
        application/xml+rss
        application/rss+xml
        application/atom+xml
        image/svg+xml
        font/ttf
        font/otf
        application/vnd.ms-fontobject;

    # text/html is always compressed (implicitly, cannot disable)
    # DON'T compress already-compressed: jpg, png, gif, mp4, zip, gz
}

Gzip 압축 레벨

comp_level은 CPU와 압축의 절충입니다. 6이 스위트 스팟이며 9는 출력이 2% 미만 작아질 뿐 CPU를 훨씬 더 씁니다. min_length는 gzip 헤더 오버헤드가 절약을 초과하는 작은 응답의 압축을 피합니다. gzip_disable은 gzip 지원이 깨진 레거시 IE6을 제외합니다.

nginx
http {
    gzip on;
    gzip_comp_level 6;  # 1-9, higher = more compression, more CPU

    # level 1: fast, low compression
    # level 6: good balance (recommended default)
    # level 9: slow, marginal size gain

    # minimum response size to compress (bytes)
    gzip_min_length 256;

    # disable gzip for old browsers
    gzip_disable "MSIE [1-6]\.";
}

Gzip Static

gzip_static은 미리 만든 .gz 파일을 제공해 런타임 압축 CPU 비용을 없앱니다. 빌드 단계가 원본 옆에 .gz 파일을 만듭니다. nginx는 Accept-Encoding: gzip을 보내는 클라이언트에게 .gz를, 그 외에는 원본을 줍니다. 정적 에셋 파이프라인에 이상적입니다.

nginx
# serve pre-compressed .gz files (no runtime compression cost)
# requires ngx_http_gzip_static_module

location / {
    gzip_static on;
    # on:     serve .gz if it exists
    # always: serve .gz even without Accept-Encoding header

    root /var/www/html;
}

# pre-compress files at build time:
# find /var/www/html -type f ( -name "*.css" -o -name "*.js" \
#   -o -name "*.html" ) -exec gzip -k -9 {} \;
# creates file.css.gz, file.js.gz alongside the originals

Brotli

Brotli는 텍스트 콘텐츠에서 gzip보다 낫습니다. 특히 높은 압축 레벨에서. 서드파티 ngx_brotli 모듈이 필요합니다. brotli_static은 미리 만든 .br 파일을 제공합니다. 최신 브라우저는 Accept-Encoding에 'br'을 광고하므로 nginx가 가능한 최선을 고릅니다.

nginx
# requires ngx_brotli module (not built-in)
http {
    brotli on;
    brotli_comp_level 6;
    brotli_types
        text/plain
        text/css
        application/javascript
        application/json
        image/svg+xml;

    # serve pre-compressed .br files
    brotli_static on;
}

# Brotli typically 10-20% smaller than gzip for text
# supported by all modern browsers (not IE)
# nginx can serve both .br and .gz; picks based on Accept-Encoding

Gzip Proxied

기본적으로 nginx는 프록시된 응답을 압축하지 않습니다(이미 압축된 업스트림의 이중 압축 방지). gzip_proxied any가 모든 프록시된 요청에서 이를 켭니다. gzip_vary가 캐시가 압축/비압축 클라이언트의 별도 버전을 저장하게 합니다.

nginx
http {
    gzip on;
    gzip_proxied any;
    # gzip_proxied controls compression for proxied requests:
    # off:           never compress proxied requests
    # expired:       compress if response has Expires header
    # no-cache:      compress if Cache-Control: no-cache
    # no-store:      compress if Cache-Control: no-store
    # private:       compress if Cache-Control: private
    # no_last_modified: compress if no Last-Modified header
    # no_etag:       compress if no ETag header
    # auth:          compress if Authorization header present
    # any:           compress all proxied requests

    gzip_vary on;  # add "Vary: Accept-Encoding" header
}
09

캐싱

Proxy Cache

proxy_cache는 업스트림 응답을 디스크에 저장합니다. keys_zone이 캐시 키의 공유 메모리 존을 정의합니다(10m ≈ 80,000 키). max_size가 디스크 사용을 제한하고, inactive가 그 시간 동안 접근되지 않은 항목을 제거합니다. use_temp_path=off는 속도를 위해 캐시에 바로 씁니다.

nginx
http {
    # define cache zone on disk
    proxy_cache_path /var/cache/nginx levels=1:2
        keys_zone=api_cache:10m
        max_size=1g
        inactive=60m
        use_temp_path=off;

    server {
        location /api/ {
            proxy_pass http://backend;
            proxy_cache api_cache;
            proxy_cache_valid 200 10m;
            proxy_cache_valid 404 1m;
        }
    }
}

Cache Zone

levels=1:2는 캐시 키의 MD5 해시에서 2단계 디렉터리 트리를 만들어 한 디렉터리의 파일 수를 줄입니다. 콘텐츠 타입별로 별도 존을 두면 max_size와 inactive를 독립적으로 튜닝할 수 있습니다. 정적은 길게, API는 짧게 캐시.

nginx
http {
    proxy_cache_path /var/cache/nginx
        levels=1:2              # directory hierarchy depth
        keys_zone=my_cache:10m  # zone name + shared memory size
        max_size=1g             # max disk size for cache
        inactive=60m            # remove if not accessed in 60min
        use_temp_path=off;      # write directly (faster, no temp copy)

    # multiple zones for different content types
    proxy_cache_path /var/cache/static levels=1:2
        keys_zone=static:10m max_size=500m inactive=24h;
    proxy_cache_path /var/cache/api levels=1:2
        keys_zone=api:10m max_size=200m inactive=10m;
}

Cache Key

캐시 키가 캐시의 고유성을 결정합니다. 기본 키는 가상 호스트 간 충돌을 일으킬 수 있으니 $host를 포함하세요. 사용자별 콘텐츠에는 사용자 식별자를 포함합니다. proxy_cache_bypass는 캐시를 건너뛰고(저장은 함) proxy_no_cache는 응답을 저장하지 않습니다.

nginx
location / {
    proxy_pass http://backend;
    proxy_cache api_cache;

    # default key: $scheme$proxy_host$request_uri
    proxy_cache_key "$scheme$request_method$host$request_uri";

    # include user-specific data to avoid cross-user leaks
    proxy_cache_key "$scheme$host$request_uri$http_x_user_id";

    # bypass cache for authenticated users
    proxy_cache_bypass $http_authorization;
    proxy_no_cache $http_authorization;
}

캐시 유효성

proxy_cache_valid가 상태 코드별 TTL을 설정합니다. 0s 또는 상태 생략은 그 상태의 캐싱을 막습니다. proxy_cache_lock은 같은 키의 동시 캐시 미스를 직렬화해 한 요청만 업스트림을 치고 나머지는 캐시된 응답을 기다립니다.

nginx
location / {
    proxy_pass http://backend;
    proxy_cache api_cache;

    # cache by response status code
    proxy_cache_valid 200 302 10m;
    proxy_cache_valid 404 1m;
    proxy_cache_valid 500 502 503 504 0s;  # don't cache errors

    # fallback for any other status
    proxy_cache_valid any 1m;

    # cache lock: collapse concurrent misses into one upstream call
    proxy_cache_lock on;
    proxy_cache_lock_timeout 5s;
}

캐시 우회

proxy_cache_bypass는 캐시 읽기를 건너뜁니다(업스트림으로 가며, 저장은 할 수 있음). proxy_no_cache는 저장을 건너뜁니다. X-Cache-Status 헤더는 디버깅에 귀중합니다. HIT는 캐시에서 제공, MISS는 업스트림에서 가져옴을 뜻합니다.

nginx
location / {
    proxy_pass http://backend;
    proxy_cache api_cache;

    # bypass cache (always go to upstream)
    proxy_cache_bypass $http_authorization $arg_nocache;

    # don't store in cache
    proxy_no_cache $http_authorization;

    # add header showing cache status for debugging
    add_header X-Cache-Status $upstream_cache_status;
}

# $upstream_cache_status values:
# MISS, BYPASS, EXPIRED, STALE, UPDATING, REVALIDATED, HIT

브라우저 캐싱

브라우저 캐싱은 재방문 지연을 줄입니다. immutable은 재검증을 완전히 건너뜁니다(내용 기반 파일명에만 안전). no-cache는 매번 재검증이며(조건부 GET은 여전히 허용) no-store는 절대 저장하지 않음입니다. 효율적인 304 응답을 위해 ETag와 함께 쓰세요.

nginx
# cache static assets in the browser
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2?)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
}

# HTML - revalidate always
location ~* \.html$ {
    add_header Cache-Control "no-cache, must-revalidate";
    etag on;
}

# API responses - never cache
location /api/ {
    add_header Cache-Control "no-store";
}

# public:    any cache (browser, CDN) may store
# private:   only the browser may store
# immutable: file never changes, skip revalidation
# no-store:  never cache
10

URL Rewrite

return 디렉티브

return이 리다이렉트나 응답의 가장 단순한 방법이며 처리를 즉시 중단합니다. 영구 리다이렉트는 301, 임시는 302를 쓰세요. 상태 코드에 본문(200, 418)이나 URL 리다이렉트를 반환할 수 있습니다. 리다이렉트에는 rewrite보다 return을 선호하세요.

nginx
# simplest redirect/rewrite - return stops processing
server {
    location /old {
        return 301 /new;
    }

    location /external {
        return 301 https://example.com$request_uri;
    }

    location /api {
        return 200 "OK\n";
    }

    location /teapot {
        return 418 "I'm a teapot";
    }
}

# return is preferred over rewrite for simple redirects

rewrite 디렉티브

rewrite는 URI를 정규식으로 매칭해 교체합니다. last는 새 URI로 location 매칭을 다시 평가하고(처음부터 다시), break는 rewriting을 멈추지만 현재 location에 머뭅니다. redirect/permanent는 브라우저에 리다이렉트를 보냅니다.

nginx
# rewrite regex replacement [flag]
server {
    # rewrite /old/* to /new/* preserving the captured part
    rewrite ^/old/(.*)$ /new/$1 permanent;

    # rewrite old blog URLs to new structure
    rewrite ^/blog/(\d{4})/(\d{2})/(.*)$ /articles/$1/$2/$3 last;

    # capture with named groups
    rewrite ^/download/(.*)$ /assets/$1 last;
}

# flags:
# last:      re-search locations with the new URI
# break:     stop rewrite, continue in current location
# redirect:  302 temporary redirect
# permanent: 301 permanent redirect

Rewrite 플래그

last vs break가 가장 혼란스러운 부분입니다. last는 location 탐색을 다시 실행하고(rewrite가 다른 location을 겨냥할 때 유용), break는 rewriting을 멈추고 머뭅니다(rewrite가 내부 경로만 조정할 때 유용). redirect/permanent는 브라우저의 URL을 바꿉니다.

nginx
location / {
    # last: restart location matching with new URI
    rewrite ^/api/(.*)$ /backend/$1 last;

    # break: stop processing rewrites, stay in current location
    rewrite ^/static/(.*)$ /assets/$1 break;

    # redirect: 302 temporary redirect (browser URL changes)
    rewrite ^/old/(.*)$ /new/$1 redirect;

    # permanent: 301 permanent redirect (browser URL changes)
    rewrite ^/old/(.*)$ /new/$1 permanent;
}

# avoid rewrite inside if blocks - use location + try_files instead

Named Capture

named capture(?<name>pattern)는 위치 기반 $1, $2보다 명확한 변수($name)를 만듭니다. location 정규식과 rewrite 모두에서 동작합니다. 캡처된 값은 그 location 안의 proxy_pass, fastcgi_param, add_header, log_format에서 사용할 수 있습니다.

nginx
# named captures in regex locations
location ~ ^/users/(?<username>[a-z]+)/?$ {
    proxy_pass http://backend/users/$username;
}

# named captures in rewrite
location / {
    rewrite ^/articles/(?<year>\d{4})/(?<slug>[a-z-]+)/?$
        /blog?year=$year&slug=$slug last;
}

# named captures become variables: $year, $slug, $username
# accessible in proxy_pass, fastcgi_pass, headers, etc.
# safer than $1, $2 positional captures for readability

map 디렉티브

map은 한 변수에서 다른 변수로의 룩업 테이블을 만들며 지연 평가됩니다. if 문 사슬보다 훨씬 효율적이고 읽기 좋습니다. default 분기가 매칭되지 않은 값을 처리하고, 정규식 매칭(~ 접두어)은 순서대로 검사됩니다.

nginx
# map creates a new variable based on another variable's value
map $http_host $backend {
    default            "http://default.backend";
    "a.com"            "http://a.backend";
    "b.com"            "http://b.backend";
    "~^.*\.app\.com$" "http://app.backend";
}

server {
    server_name a.com b.com;
    location / {
        proxy_pass $backend;
    }
}

# map is evaluated lazily and cached per request
# more efficient than if/else chains

if 디렉티브 (주의)

if는 location 블록 안에서 놀라운 동작을 보이며 설정을 예측 불가능하게 재작성할 수 있습니다. 보편적으로 안전한 용도는 return과 rewrite뿐입니다. 파일 존재 확인은 try_files, 복잡한 로직은 map이나 별도 location 블록을 쓰세요. 위키의 'If Is Evil'을 참고하세요.

nginx
# "if is evil" — use sparingly! Only safe for:
# return / rewrite, and with these checks:
#   -f, -d, -e, -x (file/dir/exists/executable)
#   =, !=, ~, ~* (string/regex comparison)

location / {
    if ($request_method = POST) {
        return 405;
    }

    if ($http_user_agent ~* "bot") {
        return 403;
    }

    # BAD: don't do this inside if
    # if (-f $request_filename) { ... }
    # use try_files instead
    try_files $uri $uri/ /index.html;
}
11

Redirect

영구 리다이렉트 (301)

301은 '영구 이동'을 뜻하며 브라우저와 검색엔진이 캐시하므로 진짜 영구적인 변화에만 쓰세요. 실수를 고정하지 않도록 먼저 302로 테스트하세요. 301은 링크 자산(SEO)을 새 URL로 넘깁니다.

nginx
# 301 - permanent redirect (cached by browsers indefinitely)
server {
    listen 80;
    server_name old-domain.com;

    # redirect entire site to a new domain
    return 301 https://new-domain.com$request_uri;
}

location /old-page {
    return 301 /new-page;
}

# 301 caches indefinitely in browsers — test with 302 first!
# Search engines treat 301 as a permanent move and update indexes.

임시 리다이렉트 (302)

302는 리다이렉트 시 POST를 GET으로 바꿉니다(역사적 동작). 307과 308은 메서드를 유지하며 POST 재제출에 중요합니다. 303은 명시적으로 GET으로 변환합니다(폼 제출 후 새로고침 시 이중 제출 방지에 유용). 메서드를 유지해야 하는지에 따라 고르세요.

nginx
# 302 - temporary redirect (not cached by default)
location /maintenance {
    return 302 /maintenance.html;
}

# 307 - temporary, preserves HTTP method (POST stays POST)
location /api/v1 {
    return 307 /api/v2;
}

# 308 - permanent, preserves HTTP method
location /api/v1 {
    return 308 /api/v2;
}

# 303 - see other (always uses GET for the new request)
location /form-submit {
    return 303 /success;
}

www → non-www 리다이렉트

한 가지 표준 형식(www 또는 non-www)을 정하고 나머지를 리다이렉트하세요. 두 server 블록이 가장 깔끔한 패턴입니다. 표준이 아닌 쪽은 리다이렉트만 합니다. $request_uri가 경로와 쿼리 문자열을 유지합니다. HTTPS 리다이렉트에도 같은 로직을 적용하세요.

nginx
# www to non-www
server {
    listen 80;
    server_name www.example.com;
    return 301 https://example.com$request_uri;
}

server {
    listen 80;
    server_name example.com;
    # ... main site config
}

# non-www to www (reverse direction)
server {
    listen 80;
    server_name example.com;
    return 301 https://www.example.com$request_uri;
}

HTTP → HTTPS 리다이렉트

$host가 원래 호스트명을 유지하므로 리다이렉트가 모든 server_name에서 동작합니다. $request_uri가 경로와 쿼리를 유지합니다. 비표준 포트는 $host에 :port를 덧붙이세요. 전용 80포트 server 블록이 location마다 if 검사하는 것보다 깔끔합니다.

nginx
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}

# with a non-standard HTTPS port
server {
    listen 8080;
    return 301 https://$host:8443$request_uri;
}

# redirect only a specific path
location /secure {
    if ($scheme = http) {
        return 301 https://$host$request_uri;
    }
}

다른 도메인으로 리다이렉트

도메인 이전에는 $request_uri가 전체 경로와 쿼리를 유지해 링크가 깨지지 않습니다. 경로 구조가 바뀔 때는 캡처가 있는 rewrite를 쓰세요. 영구 이전에는 301이 맞으며 SEO 순위를 새 도메인으로 이전합니다.

nginx
# domain migration — preserve all paths
server {
    listen 80;
    server_name old.com www.old.com;
    return 301 https://new.com$request_uri;
}

# preserve path and query string
location /docs/ {
    return 301 https://docs.new.com$request_uri;
}

# with path rewrite using capture groups
location /old-blog/ {
    rewrite ^/old-blog/(.*)$ https://blog.new.com/$1 permanent;
}

경로 기반 리다이렉트

경로 리다이렉트는 URL 정리(후행 슬래시 제거, 파일 확장자 제거)와 콘텐츠 이동에 유용합니다. 캡처($1)가 있는 정규식 location이 유연한 경로 재작성을 가능하게 합니다. 쿼리 파라미터 기반 리다이렉트는 $arg_name으로 개별 쿼리 파라미터를 읽습니다.

nginx
# redirect specific paths
location /promo/2023 {
    return 301 /promo/2024;
}

# remove trailing slash
location ~ ^/(.*)/$ {
    return 301 /$1;
}

# remove .html extension
location ~ ^/(.*)\.html$ {
    return 301 /$1;
}

# redirect based on query parameter
location /download {
    if ($arg_version = "1") {
        return 301 /download?v=2;
    }
}
12

FastCGI (PHP-FPM)

PHP-FPM 기본 구성

fastcgi_pass는 PHP 요청을 UNIX 소켓(더 빠르고 로컬 전용)이나 TCP 포트로 PHP-FPM에 보냅니다. include fastcgi_params가 표준 CGI 변수를 설정하고, SCRIPT_FILENAME이 실행할 PHP 파일을 알려 줍니다. 문서 루트와 스크립트 경로를 결합합니다.

nginx
server {
    listen 80;
    server_name example.com;
    root /var/www/laravel/public;
    index index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;
        # or: fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

FastCGI Params

fastcgi_params는 PHP에 전달되는 환경 변수를 설정합니다. SCRIPT_FILENAME이 가장 중요하며 없으면 PHP가 스크립트를 찾지 못합니다. 커스텀 파라미터(APP_ENV, DB_HOST)는 앱을 수정하지 않고 설정을 주입하게 합니다. PATH_INFO는 일부 프레임워크에서 클린 URL을 가능하게 합니다.

nginx
location ~ \.php$ {
    fastcgi_pass unix:/run/php/php-fpm.sock;

    # standard CGI parameters
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;

    # custom application parameters
    fastcgi_param APP_ENV production;
    fastcgi_param DB_HOST db.internal;

    # flag for HTTPS (so PHP knows the original scheme)
    fastcgi_param HTTPS $https_flag;
}

FastCGI Cache

fastcgi_cache는 PHP 응답을 저장해 캐시 가능한 페이지의 부하를 극적으로 줄입니다. fastcgi_cache_use_stale은 백엔드 오류나 타임아웃 시 오래된 캐시 응답을 제공해 복원력을 높입니다. 사용자별 또는 인증된 콘텐츠를 캐시하지 않도록 주의하세요.

nginx
http {
    fastcgi_cache_path /var/cache/nginx/php
        levels=1:2
        keys_zone=phpcache:100m
        max_size=1g
        inactive=60m;

    server {
        location ~ \.php$ {
            fastcgi_pass unix:/run/php/php-fpm.sock;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

            fastcgi_cache phpcache;
            fastcgi_cache_valid 200 10m;
            fastcgi_cache_key $scheme$host$request_uri;
            fastcgi_cache_use_stale error timeout invalid_header;
        }
    }
}

FastCGI 버퍼

버퍼는 클라이언트로 보내기 전 PHP 응답을 담습니다. 버퍼가 작으면 큰 응답에서 nginx가 디스크에 씁니다(느림). 'upstream sent too big header' 오류가 보이면 fastcgi_buffer_size를 늘리세요. 큰 API 응답에는 더 크고 적은 버퍼를 쓰세요.

nginx
location ~ \.php$ {
    fastcgi_pass unix:/run/php/php-fpm.sock;

    # buffer settings
    fastcgi_buffering on;
    fastcgi_buffer_size 16k;
    fastcgi_buffers 16 16k;
    fastcgi_busy_buffers_size 32k;

    # for large responses (e.g., PHP generating big JSON)
    fastcgi_buffers 64 16k;
    fastcgi_buffer_size 32k;

    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

FastCGI 타임아웃

fastcgi_read_timeout은 nginx가 PHP의 출력을 기다리는 시간입니다. 장기 실행 스크립트(데이터 임포트, 보고서 생성, AI 호출)에는 더 높은 값이 필요합니다. PHP의 max_execution_time이 최소한 같거나 높아야 하며, 그렇지 않으면 PHP가 먼저 타임아웃됩니다.

nginx
location ~ \.php$ {
    fastcgi_pass unix:/run/php/php-fpm.sock;

    fastcgi_connect_timeout 5s;
    fastcgi_read_timeout 300s;    # for long-running scripts
    fastcgi_send_timeout 300s;

    # increase for very slow PHP scripts (imports, exports, reports)
    fastcgi_read_timeout 600s;
}

# also adjust max_execution_time in php.ini to match
# otherwise PHP kills the script before nginx times out

PHP와 try_files

try_files $uri $uri/ /index.php?$args가 PHP 프레임워크(WordPress, Laravel, Drupal)의 표준 패턴입니다. 실제 파일/디렉터리를 제공하고, 아니면 쿼리 문자열과 함께 index.php로 라우팅합니다. $args가 원래 쿼리 파라미터를 유지합니다.

nginx
# WordPress-style pretty URLs
server {
    root /var/www/wordpress;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

    # deny access to sensitive files
    location ~* /wp-config.php {
        deny all;
    }
}
13

WebSocket Proxy

WebSocket 프록시

WebSocket은 HTTP/1.1과 Upgrade, Connection 헤더가 필요합니다. map 블록이 클라이언트의 Upgrade 헤더를 올바른 Connection 값으로 변환합니다. WebSocket은 'upgrade', 일반 HTTP는 'close'. 긴 read_timeout이 유휴 WebSocket 연결을 유지합니다.

nginx
# Map the Upgrade header to a Connection value
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 80;
    server_name ws.example.com;

    location / {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;

        proxy_read_timeout 3600s;  # 1 hour
        proxy_send_timeout 3600s;
    }
}

Upgrade 헤더

WebSocket에는 HTTP/1.1이 필수입니다(HTTP/2는 멀티플렉싱을 다르게 다룸). Connection을 'upgrade'로 고정할 수 있지만 map 변수 방식은 같은 location의 비WebSocket 요청도 처리합니다. 백엔드가 Origin 헤더를 검증할 수 있도록 Host를 전달하세요.

nginx
location /ws {
    proxy_pass http://backend;

    # HTTP/1.1 is required for the Upgrade mechanism
    proxy_http_version 1.1;

    # pass the Upgrade header through
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";

    # preserve host for origin checks on the backend
    proxy_set_header Host $host;

    # real client IP
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

WebSocket 타임아웃

기본 proxy_read_timeout(60s)은 유휴 WebSocket 연결을 닫습니다. 메시지 사이 연결을 유지하려 높게 설정하세요(86400s = 24시간). proxy_buffering off는 메시지가 배칭되지 않고 즉시 클라이언트에 도달하게 합니다.

nginx
location /ws {
    proxy_pass http://backend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;

    # WebSocket connections are long-lived
    # default 60s would close them during idle periods
    proxy_read_timeout 86400s;  # 24 hours
    proxy_send_timeout 86400s;

    # disable buffering for real-time messages
    proxy_buffering off;
}

Socket.io 프록시

Socket.io는 HTTP 롱폴링으로 시작해 가능하면 WebSocket으로 업그레이드합니다. 두 전송 모두 같은 proxy_pass를 지나므로 하나의 location이 전부 처리합니다. X-Forwarded-Proto를 전달하면 socket.io가 HTTPS 뒤임을 알고 올바른 URL을 만듭니다.

nginx
server {
    listen 80;
    server_name socket.example.com;

    location / {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Host $host;

        proxy_read_timeout 86400s;

        # socket.io needs these for correct client IP and scheme
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

# socket.io uses both polling (HTTP) and WebSocket transports
# both are handled by the proxy_pass above

여러 WebSocket 경로

서로 다른 WebSocket 서비스는 경로로 다른 백엔드에 라우팅할 수 있습니다. 각 location은 같은 upgrade 헤더가 필요합니다. map 블록은 http 수준에서 한 번 정의되어 공유됩니다. read_timeout은 서비스별로 튜닝하세요. 채팅은 자주 활동하고, 알림은 몇 시간 유휴일 수 있습니다.

nginx
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 80;

    # chat application
    location /ws/chat/ {
        proxy_pass http://chat_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_read_timeout 3600s;
    }

    # notifications service
    location /ws/notify/ {
        proxy_pass http://notify_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_read_timeout 86400s;
    }
}

WSS (보안 WebSocket)

WSS는 TLS 위의 WebSocket입니다. nginx가 TLS를 종료하고(인증서 처리) 백엔드에는 평문 WebSocket을 프록시합니다. 백엔드는 TLS 설정이 필요 없습니다. 표준 프로덕션 구성이며 HTTPS 페이지의 브라우저는 혼합 콘텐츠 규칙 때문에 WSS를 요구합니다.

nginx
server {
    listen 443 ssl;
    server_name ws.example.com;

    ssl_certificate     /etc/ssl/ws.example.com.crt;
    ssl_certificate_key /etc/ssl/ws.example.com.key;

    location / {
        proxy_pass http://backend:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Host $host;
        proxy_read_timeout 86400s;
    }
}

# browser connects with wss://ws.example.com
# nginx terminates TLS, proxies plain WebSocket to the backend
14

보안 헤더

X-Frame-Options

X-Frame-Options는 사이트가 iframe에 삽입되는 것을 막아 클릭재킹 공격을 차단합니다. SAMEORIGIN은 자신의 페이지가 스스로 프레임하는 것을 허용합니다. 현대적 대체물은 더 유연한 CSP frame-ancestors입니다. always는 오류 응답에도 헤더가 보내지게 합니다.

nginx
# prevent clickjacking (your site embedded in an iframe)
add_header X-Frame-Options "SAMEORIGIN" always;

# options:
# DENY          - no framing at all
# SAMEORIGIN    - only same-site can frame
# ALLOW-FROM    - deprecated, use CSP frame-ancestors instead

# modern equivalent via Content-Security-Policy
add_header Content-Security-Policy "frame-ancestors 'self'" always;

X-Content-Type-Options

nosniff는 브라우저가 Content-Type 헤더를 신뢰하고 내용을 스니핑하지 않게 합니다. 없으면 브라우저가 업로드된 이미지를 HTML 내용으로 스니핑해 HTML로 실행할 수 있습니다. 노력 대비 가치가 높은 헤더이므로 항상 켜세요.

nginx
# prevent MIME-type sniffing
add_header X-Content-Type-Options "nosniff" always;

# forces the browser to respect the declared Content-Type
# prevents XSS via uploaded files (e.g., an image containing HTML
# being executed as a script)

# related: block Adobe Flash / PDF cross-domain policies
add_header X-Permitted-Cross-Domain-Policies "none" always;

Content-Security-Policy

CSP는 XSS에 대한 가장 강력한 방어로, 스크립트, 스타일, 이미지 등의 허용 출처를 화이트리스트합니다. 아무것도 깨지 않고 위반을 찾으려 Report-Only로 시작한 뒤 강제하세요. 'self'는 같은 출처, 'unsafe-inline'은 인라인 스크립트/스타일 허용(많은 앱에 필요)입니다.

nginx
# strict CSP — restricts where resources can load from
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://api.example.com; frame-ancestors 'none'; base-uri 'none'; form-action 'self'" always;

# report-only mode (logs violations without blocking)
add_header Content-Security-Policy-Report-Only "default-src 'self'; report-uri /csp-report" always;

X-XSS-Protection

X-XSS-Protection은 브라우저 내장 반사 XSS 필터를 켰습니다. 최신 브라우저는 CSP를 선호해 이 기능을 제거했습니다. mode=block은 (새 취약점을 들일 수 있는) 살균을 막고 페이지를 차단했습니다. 레거시 브라우저를 위해 넣어도 무해하지만 진짜 방어는 CSP입니다.

nginx
# legacy XSS auditor (older browsers)
add_header X-XSS-Protection "1; mode=block" always;

# values:
# 0              - disable the filter
# 1              - enable (sanitize)
# 1; mode=block  - enable and block the page entirely

# NOTE: deprecated in modern browsers (Chrome, Edge, Safari removed it)
# CSP is the modern replacement, but this doesn't hurt to include
# for legacy browser support

Referrer-Policy

Referrer-Policy는 사용자가 링크를 클릭할 때 Referer 헤더로 얼마나 많은 URL 정보가 새는지 제어합니다. strict-origin-when-cross-origin(브라우저 기본)은 같은 출처 요청에는 전체 URL을, 크로스 출처에는 출처만을 보내고 HTTP로 다운그레이드하면 아무것도 보내지 않습니다.

nginx
# control what the Referer header contains
add_header Referrer-Policy "strict-origin-when-cross-origin" always;

# options:
# no-referrer                  - never send Referer
# no-referrer-when-downgrade   - default; no Referer on HTTPS->HTTP
# same-origin                  - only same-site
# origin                       - send only scheme+host
# strict-origin                - origin, but not on downgrade
# origin-when-cross-origin     - full for same, origin for cross
# strict-origin-when-cross-origin - recommended default
# unsafe-url                   - send full URL (not recommended)

Permissions-Policy

Permissions-Policy는 페이지가 요청하더라도 브라우저 기능(카메라, 마이크, 지리 위치 등)을 비활성화하게 합니다. 빈 ()는 기능을 완전히 비활성화합니다. XSS의 폭발 반경을 제한합니다. 정책이 금지하면 침해된 스크립트도 카메라를 켤 수 없습니다.

nginx
# control which browser features the page can use
# (formerly Feature-Policy)
add_header Permissions-Policy "geolocation=(), microphone=(), camera=(), payment=(), usb=(), magnetometer=(), gyroscope=()" always;

# allow only for same origin
add_header Permissions-Policy "geolocation=(self), microphone=(self)" always;

# allow for specific origins
add_header Permissions-Policy "camera=(self https://trusted.com)" always;
15

접근 제어

IP별 Allow/Deny

allow/deny 규칙은 순서대로 평가되며 첫 매칭이 이깁니다. 마지막 deny all이 명시적으로 허용되지 않은 것을 모두 차단합니다. 관리 패널을 회사 IP로 잠글 때 유용합니다. 규칙은 CIDR 범위나 단일 IP를 쓸 수 있고 IPv4와 IPv6 모두 지원합니다.

nginx
location /admin {
    allow 192.168.1.0/24;     # internal network
    allow 10.0.0.0/8;         # VPN range
    allow 203.0.113.5;        # specific IP
    deny all;

    proxy_pass http://backend;
}

# rules are checked in order — first match wins
# if no rule matches, access is allowed by default

Deny All

deny all은 모두를 차단하며 allow와 함께 화이트리스트를 만듭니다. 그 반대(특정 IP 차단, 전체 허용)는 블랙리스트입니다. 화이트리스트가 더 안전합니다(기본 차단). 명시적 allow/deny가 없으면 접근이 허용되므로 제한 구역은 항상 deny all로 끝내세요.

nginx
# deny all access to a location
location /private {
    deny all;
    return 403;
}

# deny specific IPs, allow everyone else
location / {
    deny 192.168.1.100;        # block one IP
    deny 203.0.113.0/24;       # block a range
    allow all;
}

# deny a range, allow the rest
location /api {
    deny 10.0.0.0/8;
    allow all;
    proxy_pass http://backend;
}

서브넷 허용

사설 IP 대역(10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16)은 인터넷에서 라우팅되지 않으므로 이를 허용하면 내부 네트워크로 접근이 제한됩니다. IPv6에서 ::1은 localhost입니다. 내부 도구의 안전한 원격 접근에는 VPN과 결합하세요.

nginx
# allow only local/private networks
location /internal {
    allow 192.168.0.0/16;     # private class B
    allow 172.16.0.0/12;      # private class B range
    allow 10.0.0.0/8;         # private class A
    deny all;

    root /var/www/internal;
}

# IPv6
location / {
    allow 2001:db8::/32;      # example IPv6 range
    allow ::1;                # IPv6 localhost
    deny all;
}

Geo 모듈

geo는 라딕스 트리를 쓰는 IP 룩업에 최적화되어 긴 allow/deny 목록보다 훨씬 빠릅니다. 클라이언트 IP 기준으로 변수(여기서는 $allowed_ip)를 설정합니다. 'ranges' 형태는 시작-끝 IP 범위를 지원합니다. 유연한 접근 제어를 위해 if()나 map에서 변수를 사용하세요.

nginx
# map IPs to values (binary search, very fast)
geo $allowed_ip {
    default        0;
    192.168.0.0/24 1;
    10.0.0.0/8     1;
    203.0.113.5    1;
}

server {
    location /admin {
        if ($allowed_ip = 0) {
            return 403;
        }
        proxy_pass http://backend;
    }
}

# geo with IP ranges (uses 'ranges' directive)
geo $country_code {
    ranges;
    default                 ZZ;
    10.0.0.0-10.255.255.255 US;
}

IP별 제한 (limit_req)

limit_req_zone은 $binary_remote_addr(컴팩트)로 IP당 요율을 정의하고, limit_req가 이를 적용합니다. burst는 짧은 스파이크를 허용하고(최대 20까지 큐), nodelay는 대기 대신 스파이크를 즉시 처리합니다. API에 좋습니다. nodelay가 없으면 초과 요청은 거부되지 않고 지연됩니다.

nginx
http {
    # define rate limit zone (10 requests/sec per IP)
    limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;

    server {
        location /api/ {
            limit_req zone=mylimit burst=20 nodelay;
            proxy_pass http://backend;
        }
    }
}

# $binary_remote_addr uses binary form (more memory-efficient)
# 10m zone stores ~160,000 unique IP addresses
# rate=10r/s: 10 requests per second per IP
# burst=20: allow 20 requests to queue
# nodelay: serve the burst immediately (no artificial delay)

국가 차단 (GeoIP)

GeoIP 모듈은 MaxMind 데이터베이스로 클라이언트 IP를 국가 코드로 매핑합니다. map과 결합하면 국가 전체를 차단하거나 허용할 수 있습니다. 참고: MaxMind의 무료 GeoLite2는 서드파티 maxminddb 모듈이 필요합니다(레거시 GeoIP 모듈은 오래된 .dat 형식 사용). 정확도는 100%가 아니므로 거친 필터링에만 쓰세요.

nginx
# requires the GeoIP module and a MaxMind database
geoip_country /usr/share/GeoIP/GeoIP.dat;

map $geoip_country_code $allowed_country {
    default yes;
    CN no;
    RU no;
    KP no;
}

server {
    location / {
        if ($allowed_country = no) {
            return 403;
        }
        proxy_pass http://backend;
    }
}

# GeoIP2 (maxminddb module) for the newer GeoLite2 format
# maxminddb /etc/nginx/geoip2/GeoLite2-Country.mmdb;
# $geoip2_country_code source=$remote_addr country iso_code;
16

인증

Basic Auth 구성

auth_basic은 브라우저의 기본 사용자명/비밀번호 대화상자를 띄웁니다. realm 문자열('Admin Area')이 사용자에게 표시됩니다. auth_basic_user_file은 htpasswd 파일을 가리킵니다. 공개되어야 하는 하위 location에서는 auth_basic off로 인증을 끄세요.

nginx
location /admin {
    auth_basic "Admin Area";
    auth_basic_user_file /etc/nginx/.htpasswd;

    proxy_pass http://backend;
}

location /public {
    # disable auth inherited from parent location
    auth_basic off;
}

# create users with htpasswd (apache2-utils / httpd-tools):
# htpasswd -c /etc/nginx/.htpasswd user1   (create file)
# htpasswd /etc/nginx/.htpasswd user2      (append, no -c)

htpasswd 파일

htpasswd 파일은 username:hash 쌍을 저장합니다. bcrypt(-B)가 가장 강력하고, MD5(-m, 기본)는 허용 가능하며, SHA1(-s)은 약하고, PLAIN은 안전하지 않습니다. 파일 권한을 제한해 nginx만 읽게 하세요. 파일에는 유출되어선 안 되는 비밀번호 해시가 있습니다.

nginx
# /etc/nginx/.htpasswd format:
# user1:$apr1$qHR...$hashedpassword
# user2:{PLAIN}plaintext       (insecure!)
# user3:{SHA}base64sha1hash

# generate with htpasswd:
# -c  create new file (overwrites!)
# -B  bcrypt (most secure, recommended)
# -m  MD5 (default, APR1)
# -s  SHA1

# bcrypt (recommended)
# htpasswd -B /etc/nginx/.htpasswd user1

# protect the file permissions
chown root:nginx /etc/nginx/.htpasswd
chmod 640 /etc/nginx/.htpasswd

특정 Location의 인증

auth_basic은 중첩 location에 상속됩니다. 하위 경로를 공개하려 auth_basic off를 설정하세요. /admin 대부분은 인증이 필요하지만 /admin/health(헬스 체크 엔드포인트)는 모니터링 도구를 위해 자격증명 없이 접근 가능해야 할 때 유용합니다.

nginx
server {
    # no auth at server level

    location /admin {
        auth_basic "Admin";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }

    location /admin/api {
        # inherits auth from /admin
        proxy_pass http://admin_api;
    }

    location /admin/public {
        # explicitly disable inherited auth
        auth_basic off;
        proxy_pass http://public_api;
    }
}

인증과 Allow/Deny 결합

satisfy any는 IP 검사 '또는' 인증 중 하나를 통과하면 접근을 허용합니다. 내부 사용자는 비밀번호 없이, 외부 사용자는 비밀번호를 요구할 때 편리합니다. satisfy all은 둘 다 필요하며 가장 엄격한 옵션으로 매우 민감한 구역에 유용합니다.

nginx
# satisfy: ALL (default) or ANY
location / {
    # allow corporate IPs without password
    # require password from outside the corporate network
    satisfy any;

    allow 192.168.0.0/16;
    deny all;

    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/.htpasswd;

    proxy_pass http://backend;
}

# satisfy all: must pass BOTH IP check AND auth
# satisfy any: pass EITHER IP check OR auth

Auth Request 모듈

auth_request는 본 요청 전에 인증 서비스로 내부 서브요청을 보냅니다. 서비스가 토큰(JWT, 세션 쿠키 등)을 검증해 2xx(허용) 또는 401/403(거부)을 반환합니다. internal은 /auth로의 외부 접근을 막습니다. 인증을 앱과 분리합니다.

nginx
# delegate authentication to a subrequest (OAuth, JWT, etc.)
location / {
    auth_request /auth;
    proxy_pass http://backend;
}

location = /auth {
    internal;                    # can't be called directly
    proxy_pass http://auth-service/validate;
    proxy_pass_request_body off;
    proxy_set_header Content-Length "";
    proxy_set_header X-Original-URI $request_uri;
}

# auth-service returns:
# 2xx -> allow (continue to backend)
# 401/403 -> deny (return to client)
# other -> error

JWT 인증

JWT 검증은 낮은 지연을 위해 njs(nginx JavaScript 모듈)로 프로세스 내에서 하거나, auth_request로 외부 서비스에 위임할 수 있습니다. njs는 nginx 안에서 JavaScript의 부분집합을 실행합니다. 빠르지만 제한적입니다. auth_request 방식이 더 유연하고 언어 무관입니다.

nginx
# requires the njs (nginx JavaScript) module
js_import auth.js;

location /api/ {
    js_content auth.validateJwt;
    proxy_pass http://backend;
}

# auth.js defines the validateJwt function:
# function validateJwt(r) {
#     var token = r.headersIn.Authorization;
#     if (!token || !verifyJwt(token)) {
#         r.return(401);
#         return;
#     }
# }

# alternative: use auth_request with an external JWT validator service
# more portable than njs, but adds a network hop per request
17

로깅

Access Log

access_log가 모든 요청을 기록합니다. log_format이 캡처할 필드를 정의합니다. 기본 'combined' 형식은 Apache 호환입니다. 트래픽 많은 사이트에서는 buffer+flush가 쓰기를 배칭해 디스크 I/O를 줄입니다. syslog는 로그를 집계를 위해 중앙 서버로 보냅니다.

nginx
http {
    log_format main '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent"';

    access_log /var/log/nginx/access.log main;
    # or use the built-in 'combined' format
    access_log /var/log/nginx/access.log combined;
}

# disable access log
access_log off;

# log to syslog
access_log syslog:server=localhost,facility=local7 main;

# buffer writes (reduce I/O)
access_log /var/log/nginx/access.log main buffer=32k flush=5s;

Error Log

error_log는 nginx 오류와 업스트림 문제를 기록합니다. 레벨이 심각도를 필터하며 warn이 좋은 기본입니다. debug는 매우 장황하고(문제 해결 전용) 디버그 빌드가 필요합니다. memory:는 로그를 RAM에 버퍼링합니다. 디스크 로깅으로는 잡을 수 없는 시작 문제 진단에 유용합니다.

nginx
# error log location and severity level
error_log /var/log/nginx/error.log warn;

# levels (low to high severity):
# debug, info, notice, warn, error, crit, alert, emerg

# debug requires nginx built with --with-debug
error_log /var/log/nginx/error.log debug;

# log to memory (for debugging, lost on restart)
error_log memory:32m debug;

# disable (NOT recommended — hides real errors)
error_log /dev/null crit;

로그 형식

커스텀 로그 형식은 필요한 것을 캡처합니다. request_time은 총 처리 시간이고, upstream_response_time은 백엔드를 분리합니다. escape=json은 로그 수집기(ELK, Loki, Datadog)를 위한 유효한 JSON을 만듭니다. escape=json이 없으면 URI의 특수 문자가 JSON 파싱을 깨뜨릴 수 있습니다.

nginx
http {
    # combined (Apache-compatible, the default)
    log_format combined '$remote_addr - $remote_user [$time_local] '
                        '"$request" $status $body_bytes_sent '
                        '"$http_referer" "$http_user_agent"';

    # main with upstream timing
    log_format main '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent" '
                    'rt=$request_time uct="$upstream_connect_time" '
                    'urt="$upstream_response_time"';

    # JSON format for log aggregation (ELK, Loki, etc.)
    log_format json escape=json
        '{"time":"$time_iso8601",'
        '"remote":"$remote_addr",'
        '"method":"$request_method",'
        '"uri":"$request_uri",'
        '"status":$status,'
        '"bytes":$body_bytes_sent,'
        '"ua":"$http_user_agent"}';
}

조건부 로깅

if= 파라미터가 변수 기반으로 조건부 로깅합니다. map $status로 오류(4xx/5xx)만 로그하면 트래픽 많은 사이트의 노이즈와 디스크 사용이 줄어듭니다. 변수가 0/빈 값이면 로깅을 건너뛰고 0이 아니면 로그합니다.

nginx
http {
    # don't log successful 2xx/3xx, only errors
    map $status $loggable {
        ~^[23]  0;
        default 1;
    }

    server {
        access_log /var/log/nginx/access.log main if=$loggable;
    }
}

# skip logging for static assets
map $request_uri $log_skip {
    default                    1;
    ~*\.(jpg|png|gif|css|js)$  0;
}
access_log /var/log/nginx/access.log main if=$log_skip;

로그 로테이션

logrotate가 오래된 로그의 이름을 바꾸고 압축합니다. postrotate가 nginx에 USR1을 보내 로그 파일을 다시 열게 하며, 이게 없으면 nginx는 이름이 바뀐 파일에 계속 씁니다. sharedscripts는 postrotate를 (파일마다가 아니라) 한 번 실행하고, delaycompress는 두 번째 로테이션에 압축해 가장 최근 로그는 압축되지 않게 합니다.

nginx
# logrotate config: /etc/logrotate.d/nginx
/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        if [ -f /var/run/nginx.pid ]; then
            kill -USR1 $(cat /var/run/nginx.pid)
        fi
    endscript
}

# USR1 signal tells nginx to reopen log files
# without dropping connections
# nginx -s reopen does the same thing

로깅 비활성화

헬스 체크와 정적 에셋의 access_log를 끄면 로그 노이즈와 디스크 I/O가 크게 줄어듭니다. log_not_found off가 404 로그 항목을 억제합니다(favicon.ico에 유용). error_log는 최소 'error' 수준으로 항상 켜 두세요. 조용한 실패는 진단이 어렵습니다.

nginx
# disable access log entirely
access_log off;

# disable for a specific location
location /health {
    access_log off;
    return 200 "ok\n";
}

# disable for static assets
location ~* \.(jpg|png|gif|ico|css|js)$ {
    access_log off;
    log_not_found off;
}

# only log errors (reduce error log verbosity)
error_log /var/log/nginx/error.log error;
18

Rate Limiting

limit_req_zone

limit_req_zone은 변수(보통 클라이언트 IP)로 키잡는 요율 한도를 정의합니다. 존 크기(10m)가 추적 가능한 고유 키 수를 결정하고, rate가 허용 요청 빈도입니다. 존은 http 컨텍스트에서 정의하고 location 컨텍스트에서 limit_req로 적용하세요.

nginx
http {
    # 10 requests per second per IP
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

    # 1 request per second per IP (for login)
    limit_req_zone $binary_remote_addr zone=login:10m rate=1r/s;

    # 100 requests per minute per IP
    limit_req_zone $binary_remote_addr zone=general:10m rate=100r/m;
}

# $binary_remote_addr uses binary form (more memory-efficient than text)
# 10m zone stores ~160,000 unique IP addresses
# rate can be per second (r/s) or per minute (r/m)

limit_req

limit_req는 location에 존을 적용합니다. burst가 짧은 스파이크를 허용하고(초과 N개까지 큐), nodelay는 간격을 두지 않고 스파이크를 전속력으로 처리합니다. 지연이 중요한 API에 좋습니다. burst가 없으면 요율 초과 요청은 즉시 거부됩니다.

nginx
http {
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

    server {
        location /api/ {
            limit_req zone=api burst=20 nodelay;
            proxy_pass http://backend;
        }

        location /login {
            limit_req zone=api burst=5 nodelay;
            proxy_pass http://backend;
        }
    }
}

# burst: max number of requests allowed to queue
# nodelay: serve the burst immediately (no artificial throttling)
# without burst: requests exceeding the rate get 503 immediately

limit_conn

limit_conn은 요청 비율이 아니라 동시 연결을 제한합니다. 한 IP가 수백 개의 동시 다운로드를 여는 것을 막는 데 유용합니다. limit_req(요율)와 결합하면 스파이크와 동시성 보호를 모두 제공합니다. limit_conn_zone은 같은 키 기반 존 패턴을 씁니다.

nginx
http {
    # limit concurrent connections per IP
    limit_conn_zone $binary_remote_addr zone=conn_per_ip:10m;

    # limit total connections per server name
    limit_conn_zone $server_name zone=conn_per_server:10m;

    server {
        limit_conn conn_per_ip 10;
        limit_conn conn_per_server 1000;

        location /download {
            limit_conn conn_per_ip 1;  # one download at a time per IP
            proxy_pass http://backend;
        }
    }
}

Burst Queue

burst는 초과 요청의 큐 크기입니다. nodelay는 스파이크 전체를 즉시 처리합니다(API에 좋음). delay=N은 N개를 즉시 처리하고 나머지를 설정된 요율로 조절합니다(더 부드러움). nodelay가 없으면 모든 초과 요청이 요율에 맞게 지연되어 부하가 고르게 퍼집니다.

nginx
http {
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

    server {
        location /api/ {
            # burst=20: allow 20 requests to queue
            # nodelay: serve them immediately (no artificial delay)
            limit_req zone=api burst=20 nodelay;

            # delay: first 10 immediate, next 10 delayed, rest rejected
            limit_req zone=api burst=20 delay=10;

            proxy_pass http://backend;
        }
    }
}

# without burst: requests over rate get 503 immediately
# with burst: excess requests queue (default delayed)
# nodelay: queue served at full speed (allows spikes)
# delay=N: first N immediate, rest throttled to the rate

IP별 요율 제한

엔드포인트 타입별로 적절한 요율의 별도 존을 정의하세요. API 엔드포인트는 높은 요율을 견디고, 인증 엔드포인트(로그인, 비밀번호 재설정)는 무차별 대입을 막으려 엄격한 한도가 필요하며, 업로드는 악용 방지를 위해 매우 낮은 요율이 필요합니다. burst는 정당한 스파이크에 작은 여유를 줍니다.

nginx
http {
    # different limits for different endpoints
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
    limit_req_zone $binary_remote_addr zone=auth:10m rate=1r/s;
    limit_req_zone $binary_remote_addr zone=upload:10m rate=2r/m;

    server {
        location /api/ {
            limit_req zone=api burst=20 nodelay;
        }

        location /login {
            limit_req zone=auth burst=5 nodelay;
        }

        location /upload {
            limit_req zone=upload burst=3 nodelay;
            client_max_body_size 100M;
        }
    }
}

커스텀 요율 제한 응답

기본적으로 요율 제한된 요청은 503(Service Unavailable)을 받습니다. 429(Too Many Requests)가 의미상 더 정확하고 대부분의 API가 기대하는 것입니다. error_page로 한도를 설명하는 JSON 본문을 반환하고, 클라이언트가 언제 물러나야 하는지 알도록 Retry-After 헤더를 포함하세요.

nginx
http {
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
    limit_req_status 429;  # default is 503

    server {
        location /api/ {
            limit_req zone=api burst=20 nodelay;

            # custom error response
            error_page 429 = @rate_limited;
        }

        location @rate_limited {
            default_type application/json;
            return 429 '{"error":"rate_limit_exceeded","retry_after":60}';
        }
    }
}

# also available: limit_conn_status 429;
19

성능 튜닝

worker_processes

worker_processes는 CPU 코어 수에 맞추며 auto가 자동으로 그렇게 합니다. 각 워커는 이벤트 루프로 많은 연결을 처리하는 단일 스레드 프로세스입니다. worker_cpu_affinity는 워커를 특정 코어에 고정해 캐시 지역성을 높입니다. auto 친화도는 OS 스케줄러가 결정하게 합니다.

nginx
# main context
worker_processes auto;  # one per CPU core (recommended)

# or set an explicit count
worker_processes 4;

# each worker handles connections independently
# 'auto' uses the number of available CPU cores

# CPU affinity (pin workers to specific cores)
worker_processes auto;
worker_cpu_affinity auto;

# or manual bitmask (one mask per worker)
worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000;

worker_connections

worker_connections는 워커당이며 총 용량은 worker_processes * worker_connections입니다. OS 파일 디스크립터 한도(worker_rlimit_nofile)에도 제한됩니다. nginx의 한도와 OS 한도(limits.conf 또는 systemd의 LimitNOFILE)를 둘 다 올려야 합니다. multi_accept는 대기 중인 연결을 한 번에 모두 잡습니다.

nginx
events {
    # connections per worker process
    worker_connections 4096;

    # accept multiple connections at once under high load
    multi_accept on;
}

# total max connections = worker_processes * worker_connections
# but also bounded by worker_rlimit_nofile (file descriptor limit)

# main context — raise the FD limit
worker_rlimit_nofile 65535;

# also raise system limits (outside nginx):
# /etc/security/limits.conf:
#   * soft nofile 65535
#   * hard nofile 65535

keepalive_timeout

클라이언트 keepalive는 여러 요청에 연결을 재사용해 지연을 줄입니다. keepalive_timeout은 유휴 연결이 열려 있는 시간입니다. (upstream 안의 keepalive 디렉티브인) upstream keepalive는 백엔드 연결을 캐시하며, nginx가 'close'를 보내지 않도록 Connection을 빈 값으로 설정하세요.

nginx
http {
    # keep-alive timeout (client side)
    keepalive_timeout 65s;
    keepalive_requests 1000;  # max requests per connection

    # upstream keepalive (reuse connections to backends)
    upstream backend {
        server 10.0.0.1:8080;
        keepalive 32;  # cache of 32 idle upstream connections
    }

    location / {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";  # clear to enable keepalive
    }
}

sendfile과 tcp_nopush

sendfile은 커널 수준 제로카피 경로로 파일을 보내 사용자 공간 버퍼를 우회하며 정적 파일에서 훨씬 빠릅니다. tcp_nopush는 sendfile과 함께 헤더와 파일 시작을 한 패킷에 보냅니다. tcp_nodelay는 낮은 지연을 위해 Nagle을 끕니다. aio threads가 디스크 I/O를 이벤트 루프에서 떼어냅니다.

nginx
http {
    # use kernel sendfile() for static files (zero-copy)
    sendfile on;

    # send headers + start of file in one TCP packet
    tcp_nopush on;

    # disable Nagle's algorithm (send small packets immediately)
    tcp_nodelay on;

    # for static file serving
    location /static/ {
        sendfile on;
        tcp_nopush on;
        aio threads;  # asynchronous I/O via thread pool
        root /var/www;
    }
}

# sendfile: zero-copy file transfer (kernel space, no user-space copy)
# tcp_nopush: coalesce headers + file data into one packet
# tcp_nodelay: don't wait to batch small packets (low latency)

버퍼 크기

트래픽에 맞게 버퍼를 조정하세요. client_max_body_size가 업로드 크기를 제한합니다(기본 1M. 파일 업로드에는 너무 작음). proxy/fastcgi 버퍼는 업스트림 응답을 담고 너무 작으면 디스크로 넘칩니다. large_client_header_buffers가 긴 URL/쿠키를 처리합니다. 'buffer overflow' 오류를 모니터링하세요.

nginx
http {
    # client body buffer (in-memory before writing to disk)
    client_body_buffer_size 16k;
    client_max_body_size 50m;

    # client header buffers
    client_header_buffer_size 1k;
    large_client_header_buffers 4 8k;

    # proxy buffers (responses from upstream)
    proxy_buffer_size 4k;
    proxy_buffers 8 4k;
    proxy_busy_buffers_size 16k;

    # fastcgi buffers (responses from PHP-FPM, etc.)
    fastcgi_buffer_size 4k;
    fastcgi_buffers 8 4k;
}

# if a request body exceeds client_body_buffer_size,
# nginx writes it to a temp file (slower)

Open File Cache

open_file_cache는 파일 디스크립터와 메타데이터를 캐시해 인기 파일의 반복 open()/stat() 시스템콜을 피합니다. 정적 파일 제공을 크게 빠르게 합니다. valid가 nginx가 파일을 다시 확인하는 주기를 제어하고(갱신 감지), min_uses가 일회성 요청의 캐싱을 피합니다. 반복되는 실패한 열기를 피하려 오류도 캐시하세요.

nginx
http {
    open_file_cache max=10000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    server {
        root /var/www/html;

        location / {
            open_file_cache max=10000 inactive=20s;
            open_file_cache_valid 30s;
            try_files $uri $uri/ =404;
        }
    }
}

# caches file descriptors, sizes, modification times
# reduces stat() and open() syscalls for popular files
# max=10000: cache up to 10000 files
# inactive=20s: remove if not accessed in 20 seconds
# min_uses=2: only cache files accessed 2+ times
# valid=30s: re-validate cache every 30s
20

Docker 배포

Docker에서의 Nginx

공식 nginx 이미지는 기본적으로 /usr/share/nginx/html을 제공하고 /etc/nginx에서 설정을 읽습니다. 설정과 콘텐츠를 볼륨으로 마운트하세요. :ro(읽기 전용)가 컨테이너가 호스트 파일을 수정하는 것을 막습니다. nginx -s reload는 컨테이너 재생성 없이 설정 변경을 반영합니다.

nginx
# run the official nginx image
docker run -d --name nginx \
    -p 80:80 -p 443:443 \
    -v /etc/nginx/nginx.conf:/etc/nginx/nginx.conf:ro \
    -v /var/www/html:/usr/share/nginx/html:ro \
    -v /etc/nginx/conf.d:/etc/nginx/conf.d:ro \
    nginx:latest

# interactive shell into the running container
docker exec -it nginx sh

# reload config without restarting the container
docker exec nginx nginx -s reload

# view logs
docker logs nginx
docker logs -f nginx

Docker Compose

Docker Compose는 nginx와 백엔드를 조율합니다. expose는 (호스트가 아니라) 연결된 서비스에 포트를 열고, depends_on이 백엔드를 먼저 시작하게 합니다. restart: unless-stopped은 재부팅에도 살아남지만 수동 정지는 존중합니다. nginx가 쓸 수 있도록 로그는 쓰기 권한(:ro 없음)으로 마운트하세요.

nginx
version: '3.8'
services:
  nginx:
    image: nginx:latest
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./conf.d:/etc/nginx/conf.d:ro
      - ./html:/usr/share/nginx/html:ro
      - ./certs:/etc/nginx/certs:ro
      - ./logs:/var/log/nginx
    depends_on:
      - backend
    restart: unless-stopped

  backend:
    image: myapp:latest
    expose:
      - "3000"

커스텀 Nginx 이미지

설정을 이미지에 굽면 배포가 불변이고 재현 가능해 런타임 볼륨 마운트가 필요 없습니다. alpine 변형은 이미지를 작게 유지합니다(기반 약 7MB). 자기 완결적 아티팩트를 원하는 Kubernetes나 CI/CD에 이상적입니다. 설정 갱신은 재빌드로 합니다.

nginx
# Dockerfile
FROM nginx:alpine

# copy custom config
COPY nginx.conf /etc/nginx/nginx.conf
COPY conf.d/ /etc/nginx/conf.d/

# copy static files
COPY html/ /usr/share/nginx/html/

# copy SSL certificates
COPY certs/ /etc/nginx/certs/

# build and run
# docker build -t mynginx .
# docker run -d -p 80:80 mynginx

# alpine is ~7MB; the image stays small
# bake config in for immutable deployments

볼륨 마운트

볼륨 마운트는 이미지를 재빌드하지 않고 설정을 반복 수정하게 해 개발에 이상적입니다. 디렉터리 마운트가 견고하고, 단일 파일 마운트는 호스트 파일이 없으면 깨질 수 있습니다(Docker가 대신 디렉터리를 만듦). named volume은 컨테이너 재생성에도 유지되며 Docker가 관리합니다.

nginx
# mount config and content as volumes (dev workflow)
docker run -d --name nginx \
    -p 80:80 \
    -v $(pwd)/nginx.conf:/etc/nginx/nginx.conf:ro \
    -v $(pwd)/conf.d:/etc/nginx/conf.d:ro \
    -v $(pwd)/html:/usr/share/nginx/html:ro \
    -v $(pwd)/logs:/var/log/nginx \
    nginx:alpine

# read-only mounts (:ro) for security
# logs need write access (no :ro)
# use named volumes for persistent data:
#   -v nginx_logs:/var/log/nginx

# IMPORTANT: mounting a single file (nginx.conf) requires
# the file to exist on the host, or Docker creates a directory

Docker에서의 리버스 프록시

Docker Compose에서 서비스는 서비스 이름(app1, app2)으로 서로를 찾습니다. nginx의 upstream이 이 이름들을 직접 참조할 수 있어 IP 주소가 필요 없습니다. 이로써 nginx가 컨테이너화된 앱의 강력한 로드 밸런서가 됩니다. 기본 Compose 네트워크를 쓰거나 격리를 위해 커스텀 네트워크를 정의하세요.

nginx
# nginx as reverse proxy for other containers
version: '3.8'
services:
  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
    depends_on:
      - app1
      - app2
    restart: unless-stopped

  app1:
    image: myapp:latest

  app2:
    image: myapp:latest

# nginx.conf:
# upstream apps {
#     server app1:3000;
#     server app2:3000;
# }
# server {
#     listen 80;
#     location / { proxy_pass http://apps; }
# }

헬스 체크

헬스 체크는 Docker(와 Swarm 같은 오케스트레이터)가 nginx가 실행 중인 것뿐 아니라 실제로 서비스 중인지 알게 합니다. wget --spider는 본문을 다운로드하지 않고 HTTP 상태를 검사합니다. start_period가 첫 검사를 지연해 nginx가 부팅할 시간을 줍니다. Kubernetes에서는 Docker HEALTHCHECK 대신 readiness/liveness 프로브를 사용하세요.

nginx
# Dockerfile with a health check
FROM nginx:alpine

HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD wget --quiet --tries=1 --spider http://localhost/ || exit 1

COPY nginx.conf /etc/nginx/nginx.conf

# docker-compose health check
version: '3.8'
services:
  nginx:
    image: nginx:alpine
    healthcheck:
      test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost/"]
      interval: 30s
      timeout: 3s
      retries: 3
      start_period: 5s

# start_period gives nginx time to boot before checking
# a failed health check marks the container unhealthy

Was this helpful?