서버 운영
Nginx 설정을 include로 나눠두면 관리가 편해진다
모든 서버 블록을 nginx.conf 한 파일에 쌓으면 길이가 금방 수백 줄이 된다. include 지시어로 파일을 나누면 수정할 때 찾기 쉽고 nginx -t 검증도 빠르다.
서버에 도메인이 하나둘 늘다 보면 /etc/nginx/nginx.conf가 점점 길어진다. 어느 순간부터 특정 도메인 설정을 찾으려면 파일을 위아래로 스크롤해야 하고, 잘못 건드리면 다른 사이트까지 영향을 받는다.
include 지시어 기본
Nginx는 설정 파일 안에서 include 지시어로 다른 파일을 불러올 수 있다. 와일드카드도 지원한다.
# /etc/nginx/nginx.conf
http {
include /etc/nginx/mime.types;
include /etc/nginx/conf.d/*.conf; # 이 줄 하나로 여러 파일을 로드
}
Debian/Ubuntu 기본 패키지 설치 시 /etc/nginx/sites-enabled/ 경로를 쓰는 방식도 있는데, 구조는 같다. conf.d/에 파일을 넣는 방식이 더 단순하게 관리된다고 느껴서 나는 그쪽을 쓴다.
도메인 단위로 파일을 나눈다
/etc/nginx/
├── nginx.conf # http 블록과 전역 설정만
├── conf.d/
│ ├── example.com.conf # example.com 서버 블록
│ ├── api.example.com.conf
│ └── default.conf # 기본 fallback
└── snippets/
├── ssl.conf # SSL 공통 설정
└── proxy.conf # proxy_pass 공통 헤더
snippets/ 디렉토리에 반복되는 설정을 넣고, 각 도메인 파일에서 include로 가져오면 중복을 줄일 수 있다.
# /etc/nginx/snippets/ssl.conf
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_session_cache shared:SSL:10m;
# /etc/nginx/conf.d/example.com.conf
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;
include snippets/ssl.conf; # SSL 설정 재사용
location / {
proxy_pass http://127.0.0.1:3000;
include snippets/proxy.conf;
}
}
수정 후 반드시 검증한다
파일을 나눠뒀다고 해도 실수로 세미콜론을 빠뜨리거나 블록이 닫히지 않으면 Nginx가 재시작에 실패한다. 항상 적용 전에 검증을 먼저 한다.
sudo nginx -t
# nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
# nginx: configuration file /etc/nginx/nginx.conf test is successful
sudo systemctl reload nginx # 검증 통과 후에만 적용
nginx -t는 include된 모든 파일까지 포함해서 전체 설정을 검증한다. 문법 오류가 있으면 어느 파일 몇 번째 줄인지 출력해준다.
파일이 많아져도 도메인 이름으로 바로 찾을 수 있고, 한 도메인 수정이 다른 도메인에 영향을 줄 가능성도 줄어든다. 설정 파일도 git으로 관리하면 변경 이력까지 남길 수 있다.