Tan Kim

nginx

고성능 웹 서버 / 리버스 프록시. 정적 파일 서빙, 리버스 프록시, 로드 밸런싱에 주로 사용된다.

설치

# Ubuntu
sudo apt install nginx
sudo systemctl start nginx
sudo systemctl enable nginx  # 부팅 시 자동 시작

주요 명령어

명령어 설명
nginx -t 설정 파일 문법 검사
nginx -s reload 무중단 설정 재로드
nginx -s stop 즉시 종료
systemctl reload nginx 권장 재로드 방법

디렉토리 구조

/etc/nginx/
├── nginx.conf              # 메인 설정
├── sites-available/        # 설정 파일 보관
│   └── example.com
└── sites-enabled/          # 활성화된 설정 (symlink)
    └── example.com -> ../sites-available/example.com
# 사이트 활성화 / 비활성화
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo rm /etc/nginx/sites-enabled/example.com

주요 설정 패턴

정적 파일 서빙

server {
    listen 80;
    server_name example.com;
 
    root /var/www/html;
    index index.html;
 
    location / {
        try_files $uri $uri/ =404;
    }
}

리버스 프록시

server {
    listen 80;
    server_name example.com;
 
    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';  # WebSocket
    }
}

HTTPS (SSL)

server {
    listen 443 ssl;
    server_name example.com;
 
    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
 
    location / {
        proxy_pass http://localhost:3000;
    }
}
 
# HTTP → HTTPS 리다이렉트
server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}

PHP-FPM 연동

server {
    listen 80;
    server_name example.com;
 
    root /var/www/html;
    index index.php index.html;
 
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
 
    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php5.6-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

로드 밸런싱

upstream backend {
    server 192.168.0.10:3000;
    server 192.168.0.11:3000;
    server 192.168.0.12:3000 weight=2;  # 가중치
}
 
server {
    listen 80;
    location / {
        proxy_pass http://backend;
    }
}

자주 쓰는 지시어

지시어 설명
listen 포트 지정
server_name 도메인 지정
root 문서 루트 경로
proxy_pass 리버스 프록시 대상
return 301 영구 리다이렉트
try_files 파일/디렉토리 순서대로 시도
client_max_body_size 요청 바디 최대 크기 (기본 1m)
gzip on 응답 압축 활성화

로그

# 접근 로그
tail -f /var/log/nginx/access.log
 
# 에러 로그
tail -f /var/log/nginx/error.log

메모