본문 바로가기
WebApp

[WebApp] NginX 설정 관련 .

by ds31x 2023. 8. 1.

nginx.conf 파일을 이용하여 설정한다.

기본 용어

directives란?

nginx에서 각 line에서 처음 등장하는 word를 directive라고 부르며, 이들은 각각 nginx가 특정 설정을 담당함.
directives는 크게 두 종류로 나뉨.

  • simple directive
  • block directive

block directives는 curly bracket으로 둘러싸여진 block을 값으로 가짐.
directives 뒤에 공백문자로 이후 놓인 value가 block이 아닌 경우는 simple directie이며, semicolon으로 끝난다.

context란?

구조적으로 nginx.conf는 core부분(최상위 level의 내용들)과, events block, http block으로 구성됨.

  • 최상위 level의 directives들이 놓인 곳을 main context 라고 부름
  • http block의 경우 다른 block directives를 포함하며, 이들은 http context에 있다고 지칭함.
  • context에 속한 directives들은 해당 context의 설정을 상속받음.
  • context에 속한 directives들은 자신이 상속한 context의 설정을 override할 수 있음.

각 Directive는 포함될 수 있는 Context가 정해져 있음.

include를 통한 설정 파일 분리.

또한 niginx의 설정은 기능들 단위로 나누어져서 여럿 파일로 구성되는 경우가 많음.
일반적으로 가장 main이 되는 nginx.conf 에서 나누어진 설정파일을 include directives 를 통해 읽어들임 (이 경우 include directive가 놓인 곳이 해당 설정의 내용으로 치환된다고 생각하면 됨.)

directives 설명

core부분과 events block

worker process의 갯수 및 실행권한 등을 설정함.

다음 예를 참고

user  nginx;              # nginx의 실행 프로세스(worker)를 어느 사용자로 수행할지 결정. (root 사용 시 보안이 취약해짐.)
worker_processes  1;      # 사용할 worker process의 수. nginx는 Master process와 여러 worker process로 구성 가능.

error_log  /var/log/nginx/error.log warn; # 로그 저장 경로와 로그 레벨을 지정함.
pid        /var/run/nginx.pid;            # Master process의 pid가 저장되는 경로.

events {                  # NginX의 event-driven 동작방식에 대한 설정이 이루어지는 block.
    worker_connections  1024;  # 하나의 worker process가 처리할 수 있는 connections의 숫자.
    # multi_accept on;         # default off임.
}
  • 위의 예에서 user, worker_processes 등이 simple directives임.
  • event는 block directives임.

http block

http context에 unpstream block과 server block 이 포함됨

  • serverlocation을 포함하는 block.
  • 여기서 설정된 값을 하위 block들이 상속.

nginx가 webserver로 동작하려면 적어도 하나의 server directive가 있어야 함.

upstream block

upstream block 은 Origin 서버라고 불림.

  • server block 내 locaton block 의 proxy_pass 와 연동됨.
  • proxy_pass 에서 지정된 upstream block의 이름에 따라 해당 request를 처리할 서버가 지정됨.
  • upstream block네는 proxy_pass를 통해 nginx가 받은 여러 requests를 해당 was (server에 설정된)로 넘겨짐.
  • 이 block의 server 에 실제 서비스를 수행하는 server와 port가 기재됨.

server block

server block directive는 listen direictive를 통해 ipaddress, port (or unix domain socket and path)를 지정함.

server {
    listen 127.0.0.1:8080; 
    # The rest of server configuration
}
  • port를 위의 예에선 8080으로 지정함.
  • port를 생략할 경우 80이 기본값임.

Domain Name이 있는 경우는 다음과 같이 server_name directive를 이용한다.

server {
    listen      80;
    server_name example.org www.example.org; # 정규표현식 사용가능함.
    ...
}

또한 server block은 내부에 location block을 포함한다.

  • 하나의 web site에 해당함.
  • 즉, server block이 여럿일 경우 여러 web sites를 가상 호스트 해줌.
  • 복수 개의 location block을 포함할 수 있음.
  • location block을 통해 특정 URL의 처리를 지정함.

location block

하나의 web site에 해당하는 server block 내에 존재하며, 내부의 directive를 통해 특정 URL에 따른 request처리를 다르게 지정가능함.

이를 통해 nginx는 URL에 따라 다른 server로 request를 전달해줄 수 있음.

location directive에서 사용하는 URL은 특정 경로의 일부인 prefix string이거나 정규식 표현임.

아래와 같은 예를 들어 설명하면,

server {
    location /images/ {
        root /data;
    }

    location / {
        proxy_pass http://www.example.com;
    }
}

static file 서비스를 위한 root option의 사용 방법을 위의 location이 부여줌.

  • /image/로 시작하는 URL의 경우, root 뒤의 기재된 location이 추가된 상태로 파일을 찾음.
  • 즉, /image/test.png의 경우, /data/image/test.png에서 resource를 찾아서 응답.

동적인 page를 위해 WAS등에 request를 넘겨야 하는 경우 proxy_pass 를 사용함 (아래 기재된 locatoin 참고)

  • 위에서 지정한 /image/로 시작하는 경우를 제외한 request는
  • http://www.example.com 이라는 proxy server로 전달되고, 이후 해당 proxy server의 response가 client에 전달됨.

proxy_pass directive에 upstream block의 이름을 http://뒤에 넣어줄 수도 있음.

다음 예에서 /api로 오는 URL의 request는 docker-server라는 이름의 upstream block에서 지정한 서버로 넘겨진다.

    upstream docker-server {
        server server:8080;
    }

    server {
        listen 80;
        server_name localhost;

        location / {
            root /usr/share/nginx/html;
            index index.html index.htm;
            try_files $uri $uri/ /index.html =404;
        }
        location /api {
            proxy_pass         http://docker-server;
            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }

최종 예

user  nginx;              # nginx의 실행 프로세스(worker)를 어느 사용자로 수행할지 결정. (root 사용 시 보안이 취약해짐.)
worker_processes  1;      # 사용할 worker process의 수. nginx는 Master process와 여러 worker process로 구성 가능.

error_log  /var/log/nginx/error.log warn; # 로그 저장 경로와 로그 레벨을 지정함.
pid        /var/run/nginx.pid;            # Master process의 pid가 저장되는 경로.

events {                  # NginX의 event-driven 동작방식에 대한 설정이 이루어지는 block.
    worker_connections  1024;  # 하나의 worker process가 처리할 수 있는 connections의 숫자.
    # multi_accept on;         # default off임.
}

http {                    # server와 location을 포함하는 block. 여기서 설정된 값을 하위 block들이 상속.
    include       /etc/nginx/mime.types;       # opton 항목 설정 파일의 경로 (주로 MIME type목록이 지정됨).
    default_type  application/octet-stream;    # octet stream 기반의 http를 사용 의미.

    charset utf-8;                             # encoding 설정

    server {
        listen 80;
        server_name localhost;

        location / {
            root /usr/share/nginx/html;
            index index.html index.htm;
            try_files $uri $uri/ /index.html =404;
        }
        location /api {
            proxy_pass         http://docker-server;
            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        }
        location /socket {
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Host $host;
            proxy_pass http://docker-server;
        }
    }

    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  /var/log/nginx/access.log  main;

    sendfile        on;

    server_tokens    off;    # 보안상 off권장, on일 경우 nginx의 version정보가 header에 포함됨.

    keepalive_timeout  65;  # connection을 얼마나 유지할지를 seconds로 설정. (default 10sec)

    # gzip  on;             # response의 content 압축 여부. gzip 외의 방법도 지원.


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

References

보다 자세한 location block 설정 방법 : https://rondeveloper.tistory.com/94
간략한 정리 자료 : https://www.owl-dev.me/blog/28

정리가 보다 자세한 URL 모음.

https://docs.nginx.com/nginx/admin-guide/basic-functionality/runtime-control/
https://technerd.tistory.com/19
https://gonna-be.tistory.com/20#Configuration%20File%20%EA%B5%AC%EC%A1%B0%20%EB%B6%84%EC%84%9D%ED%95%98%EA%B8%B0

그외 자료

https://coding-start.tistory.com/381

728x90