Nginx를 설치하고 실행시키면 아래와 같은 웹 페이지가 뜬다. 하지만 아래 웹 페이지가 아닌 우리가 직접 만든 웹 페이지를 띄우고 싶을 것이다. 그러려면 Nginx의 기본적인 문법을 어느 정도 알고 있어야, 설정값을 직접 수정해서 응용할 수 있다. 따라서 지금부터 Nginx의 기본 문법을 하나씩 알아보자.
✅ Nginx의 설정 파일 위치
/etc/nginx/nginx.conf
Nginx에서 가장 근본이 되는 설정 파일(루트 설정 파일)
전역적으로 설정되어야 하는 내용(워커 프로세스 개수, 로그 저장 위치 등)이 포함되어 있다.
/etc/nginx/conf.d/default.conf
기본 웹 서버(Web Server) 설정 파일
이렇게 크게 2가지 설정 파일이 존재한다. 여기서 /etc/nginx/conf.d/default.conf 파일 위주로 코드를 해석해보자.
✅ 기본적인 Nginx 문법 해석
/etc/nginx/conf.d/default.conf
server {
listen 80;
server_name localhost;
#access_log /var/log/nginx/host.access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
위 파일을 열어보면 위와 같이 코드가 작성되어 있다. 주석 부분을 빼고 보자.
/etc/nginx/conf.d/default.conf
# server : '하나의 웹 사이트에 관련된 설정'을 관리하는 단위 ('server 블럭'이라고 부름)
server {
# localhost:80으로 들어오는 요청을 이 server 블럭에서 처리하도록 설정
# (server_name이 일치하는 server 블럭이 없는 경우 첫 번째 정의되어 있는 server 블럭을 기반으로 처리)
# (아직은 정확히 몰라도 된다. 나중에 '멀티 도메인' 기능을 배우면 쉽게 이해할 수 있다.)
listen 80;
server_name localhost;
# / 으로 시작하는 모든 경로를 처리 (ex. /index.html)
location / {
# /jscode.html로 요청이 들어오면 /usr/share/nginx/html/jscode.html 파일로 응답
root /usr/share/nginx/html;
# /로 요청이 들어오면 /usr/share/nginx/html/index.html로 응답
# 만약 /usr/share/nginx/html/index.html이 없을 경우, /usr/share/nginx/html/index.htm으로 응답
index index.html index.htm;
}
# Nginx에서 500, 502, 503, 504의 상태 코드가 발생했을 때 /50x.html로 redirect
error_page 500 502 503 504 /50x.html;
# /50x.html과 완전히 일치하는 경로를 처리
location = /50x.html {
# /50x.html로 요청이 들어오면 /usr/share/nginx/html/50x.html 파일로 응답
root /usr/share/nginx/html;
}
}
주의) ‘중괄호({...}) 형태의 구문’과 ‘세미 콜론(;)으로 끝나는 구문’ 2가지가 있다. 설정 파일을 작성할 때 세미 콜론(;)을 빠트려서 에러가 뜨는 경우가 많으니 주의하자.