1. Nginx 소스 빌드 설치
1.1 소스 코드 다운로드 및 압축 해제
# 최신 안정 버전 다운로드
wget https://nginx.org/download/nginx-1.28.1.tar.gz
# 압축 해제 및 디렉토리 이동
tar -zxvf nginx-1.28.1.tar.gz
cd nginx-1.28.1/
1.2 빌드 환경 준비
필수 의존성 패키지를 설치합니다.
# Rocky Linux/RHEL 계열
dnf install -y gcc openssl-devel pcre2-devel zlib-devel
1.3 컴파일 설정 및 빌드
# configure 스크립트 실행
./configure \
--prefix=/opt/nginx \
--user=www \
--group=www \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--with-pcre \
--with-stream \
--with-stream_ssl_module \
--with-stream_realip_module
# 컴파일 및 설치
make -j$(nproc)
make install
1.4 환경 설정 및 서비스 등록
# 실행 사용자 생성
useradd -r -s /sbin/nologin -M www
# 환경 변수 설정
echo 'export PATH=$PATH:/opt/nginx/sbin' >> ~/.bash_profile
source ~/.bash_profile
# systemd 서비스 파일 생성
cat > /etc/systemd/system/nginx.service << 'EOF'
[Unit]
Description=High Performance Web Server
After=network.target
[Service]
Type=forking
ExecStartPre=/opt/nginx/sbin/nginx -t
ExecStart=/opt/nginx/sbin/nginx
ExecReload=/opt/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable --now nginx
2. 무중단 업그레이드 및 롤백
2.1 새 버전 준비 및 컴파일
wget https://nginx.org/download/nginx-1.29.4.tar.gz
tar -zxvf nginx-1.29.4.tar.gz
cd nginx-1.29.4
# 버전 정보 숨기기 (선택)
sed -i 's/NGINX_VERSION.*/NGINX_VERSION ""/' src/core/nginx.h
./configure --prefix=/opt/nginx [동일 옵션]
make
2.2 바이너리 교체 및 프로세스 전환
# 기존 바이너리 백업
cd /opt/nginx/sbin
cp -p nginx nginx.backup
# 새 바이너리 적용
cp -f /root/nginx-1.29.4/objs/nginx /opt/nginx/sbin/
# 마스터 프로세스에 신호 전송
kill -USR2 $(cat /opt/nginx/logs/nginx.pid)
# 이전 워커 프로세스 종료
kill -WINCH $(cat /opt/nginx/logs/nginx.pid.oldbin)
2.3 롤백 절차
# 새 마스터 프로세스 종료
kill -QUIT $(cat /opt/nginx/logs/nginx.pid)
# 백업 바이너리 복원
cp -p nginx.backup nginx
# 이전 마스터 프로세스 재활성화
kill -HUP $(cat /opt/nginx/logs/nginx.pid.oldbin)
3. 핵심 설정 구조
3.1 설정 파일 계층
| 파일/디렉토리 | 용도 |
| nginx.conf | 메인 설정 |
| conf.d/*.conf | 가상 호스트 설정 |
| mime.types | 파일 타입 매핑 |
| fastcgi_params | FastCGI 파라미터 |
3.2 기본 설정 예시
user www www;
worker_processes auto;
error_log /opt/nginx/logs/error.log warn;
pid /opt/nginx/logs/nginx.pid;
events {
worker_connections 4096;
use epoll;
multi_accept on;
}
http {
include mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /opt/nginx/logs/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
include /opt/nginx/conf/conf.d/*.conf;
}
4. 가상 호스트 및 Location 설정
4.1 가상 호스트 구성
server {
listen 80;
server_name app.example.com;
root /var/www/app;
index index.html index.php;
# root vs alias 차이
location /static {
root /var/www/assets; # /var/www/assets/static 경로
}
location /media {
alias /var/www/upload; # /var/www/upload 경로 (정확히 매핑)
}
}
4.2 Location 매칭 규칙
| 수정자 | 설명 | 예시 |
| = | 정확히 일치 | location = /exact |
| ^~ | 접두사 일치 (정규식 우선 무시) | location ^~ /prefix |
| ~ | 대소문자 구분 정규식 | location ~ \.php$ |
| ~* | 대소문자 무시 정규식 | location ~* \.(gif|png)$ |
| 없음 | 접두사 일치 | location /general |
4.3 정규식 활용 예시
server {
listen 80;
server_name api.example.com;
# 파일 확장자 기반 라우팅
location ~* \.(jpg|jpeg|png|webp)$ {
root /var/www/images;
expires 30d;
}
# API 엔드포인트
location ~ ^/api/v\d+ {
proxy_pass http://backend_cluster;
}
}
5. 인증 및 오류 처리
5.1 기본 인증 설정
# 비밀번호 파일 생성
htpasswd -c /opt/nginx/conf/.htpasswd admin
server {
location /secure {
auth_basic "Restricted Area";
auth_basic_user_file /opt/nginx/conf/.htpasswd;
root /var/www/private;
}
}
5.2 커스텀 오류 페이지
error_page 404 /not-found.html;
error_page 500 502 503 504 /server-error.html;
location = /not-found.html {
internal;
alias /var/www/errors/404.html;
}
5.3 try_files를 활용한 파일 검색
server {
root /var/www/site;
location / {
# 순서대로: URI → URI.html → URI/index.html → 기본값
try_files $uri $uri.html $uri/index.html /default.html;
}
}
6. 파일 서버 및 다운로드 제어
6.1 디렉토리 목록 및 다운로드
location /download {
root /var/www;
autoindex on;
autoindex_exact_size off; # 사람 읽기 쉬운 크기 표시
autoindex_localtime on; # 로컬 시간대 사용
autoindex_format html; # html/xml/json/jsonp
limit_rate 1024k; # 다운로드 속도 제한
}
7. 상태 모니터링 및 압축
7.1 stub_status 모듈
location /nginx_status {
stub_status;
allow 10.0.0.0/8;
deny all;
}
7.2 Gzip 압축 설정
http {
gzip on;
gzip_comp_level 5;
gzip_min_length 256;
gzip_types text/plain text/css application/json
application/javascript text/xml application/xml;
gzip_vary on;
gzip_static on; # .gz 파일 사전 생성 시 사용
}
8. 변수 시스템 및 echo 모듈
8.1 echo 모듈 컴파일
cd nginx-1.28.1
./configure [기존 옵션] --add-module=/path/to/echo-nginx-module
make
8.2 주요 내장 변수
| 변수 | 설명 |
| $remote_addr | 클라이언트 IP 주소 |
| $http_host | 요청 호스트 헤더 |
| $request_uri | 전체 요청 URI (파라미터 포함) |
| $document_uri | URI 경로만 (파라미터 제외) |
| $args | 쿼리 문자열 |
| $arg_name | 특정 파라미터 값 |
| $http_user_agent | 브라우저 정보 |
| $http_cookie | 쿠키 정보 |
8.3 변수 활용 예시
location /debug {
default_type text/html;
echo "Client IP: $remote_addr";
echo "Request URI: $request_uri";
echo "Query: $args";
echo "Host: $http_host";
}
9. 리퍼러 검증 및 리다이렉트
9.1 이미지 핫링크 방지
location /img {
valid_referers none blocked server_names *.example.com;
if ($invalid_referer) {
return 403;
# 또는 리다이렉트: rewrite ^/ http://example.com/forbidden.png;
}
}
9.2 URL 재작성
# flag 옵션: redirect, permanent, break, last
# 302 임시 리다이렉트
rewrite ^/old$ /new redirect;
# 301 영구 리다이렉트
rewrite ^/legacy$ /modern permanent;
# 내부 처리 중단
rewrite ^/api/(.*)$ /v2/$1 break;
9.3 HTTPS 강제 리다이렉트
server {
listen 80;
listen 443 ssl;
ssl_certificate /opt/nginx/certs/site.crt;
ssl_certificate_key /opt/nginx/certs/site.key;
if ($scheme = http) {
rewrite ^(.*)$ https://$host$1 permanent;
}
}
10. 리버스 프록시 및 로드 밸런싱
10.1 기본 프록시 설정
upstream backend {
server 192.168.1.10:8080 weight=5;
server 192.168.1.11:8080;
server 192.168.1.12:8080 backup;
}
server {
location / {
proxy_pass http://backend;
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_hide_header X-Powered-By;
proxy_pass_header Server;
}
}
10.2 동적/정적 분리
server {
location / {
proxy_pass http://static_servers;
}
location ~ \.(php|jsp|do)$ {
proxy_pass http://dynamic_servers;
}
}
10.3 4계층(TCP/UDP) 로드 밸런싱
# nginx.conf - http 블록 외부에 stream 블록 추가
stream {
upstream mysql_cluster {
server 192.168.1.10:3306 max_fails=3 fail_timeout=30s;
server 192.168.1.11:3306 max_fails=3 fail_timeout=30s;
}
server {
listen 3306;
proxy_pass mysql_cluster;
proxy_connect_timeout 5s;
proxy_timeout 300s;
}
# UDP 예시 (DNS)
upstream dns_servers {
server 192.168.1.10:53;
server 192.168.1.11:53;
}
server {
listen 53 udp;
proxy_pass dns_servers;
proxy_responses 1;
proxy_timeout 1s;
}
}
11. PHP-FPM 연동
11.1 PHP 소스 컴파일
wget https://www.php.net/distributions/php-8.3.30.tar.gz
tar -zxvf php-8.3.30.tar.gz
cd php-8.3.30
./configure \
--prefix=/opt/php \
--with-config-file-path=/opt/php/etc \
--enable-fpm \
--with-fpm-user=www \
--with-fpm-group=www \
--with-mysqli \
--with-pdo-mysql \
--with-curl \
--with-openssl \
--enable-mbstring \
--enable-gd \
--with-zlib
make -j$(nproc) && make install
11.2 PHP-FPM 설정
cp /opt/php/etc/php-fpm.conf.default /opt/php/etc/php-fpm.conf
cp /opt/php/etc/php-fpm.d/www.conf.default /opt/php/etc/php-fpm.d/www.conf
# 포트 설정
sed -i 's/listen = .*/listen = 127.0.0.1:9000/' /opt/php/etc/php-fpm.d/www.conf
systemctl enable --now php-fpm
11.3 Nginx 연동
server {
listen 80;
server_name php.example.com;
root /var/www/php;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
12. Memcached 캐시 통합
12.1 모듈 컴파일
./configure [기존 옵션] \
--add-module=/path/to/memc-nginx-module \
--add-module=/path/to/srcache-nginx-module
12.2 캐시 설정
upstream memcache {
server 127.0.0.1:11211;
keepalive 512;
}
server {
location /memc {
internal;
memc_connect_timeout 100ms;
memc_send_timeout 100ms;
memc_read_timeout 100ms;
set $memc_key $query_string;
set $memc_exptime 300;
memc_pass memcache;
}
location ~ \.php$ {
set $key $uri$args;
srcache_fetch GET /memc $key;
srcache_store PUT /memc $key;
fastcgi_pass 127.0.0.1:9000;
include fastcgi.conf;
}
}