Nginx에 대하여 | nginx 설치 및 http, https 설정하기

양승현·2023년 10월 22일
2

OpenSource

목록 보기
5/10
post-thumbnail

Nginx

  • open source webserver 및 reverse proxy server software로, 고성능 및 확장 가능한 웹 응용 프로그램을 제공하기 위해 설계된 소프트웨어이다.
  • nginx는 apach Http server와 함께 가장 많이 사용되는 웹 서버 중 하나이다.

nginx의 주요 특징 및 용도

web server

  • 정적 및 동적 웹 콘텐츠를 서빙하는데 사용된다.
  • 정적 콘텐츠(HTML, Imgae, CSS, JavaScript 등)를 빠르게 처리할 수 있으며, 요청에 따라 동적(로그인, 회원가입 등) 웹 응용 프로그램(PHP, Python, Ruby)으로 연결할 수 있다.
  • 정적인 파일을 클라이언트에게 전달하는 역할을 웹서버에서 처리하기 때문에, 동적 작업을 처리하는 WAS에 부담을 줄일수 있다.

reverse proxy

  • 클라이언트 요청을 앞단의 백엔드 서버로 전달하는 역할을 수행할 수 있으며, 이로 부하 분산 및 고가용성을 실현하는데 도움이 된다.
  • 백엔드 서버로의 요청을 균등하게 분배하고, 실패한 서버로부터 요청을 제외할 수 있다.

SSL/TLS 지원

  • HTTPS를 지원하며, SSL/TLS 암호화를 통해 보안 연결을 제공하며, 이는 웹 서버의 보안을 강화하는데 중요한 역할을 한다.

가상 호스팅

  • 하나의 웹 서버에서 여러 도메인 또는 서브도메인을 호스팅하는 가상 호스팅을 지원하며, 이는 여러 웹 사이트를 단일 서버로 운영할 수 있다.

URL redirection

  • URL redirection 및 URL 재작성을 수행할 수 있어, 트래픽 관리 및 검색 엔진 최적화에 도움을 준다.

모듈 확장성

  • 모듈 시스템을 사용하여 기능을 확장할 수 있으며, 이는 사용자 정의 모듈을 개발하거나 써드파티 모듈을 추가하여 nginx의 기능을 확장하는데 도움이 된다.

높은 성능

  • 비동기 이벤트 드리븐 아키텍처를 통해 높은 처리량과 낮은 메모리 사용량을 제공하며, 이는 웹 서버 및 리버스 프록시로서 높은 성능을 보장한다.

커뮤니티 지원

  • 오픈 소스 프로젝트이며, 오픈 소스 특성상 활발한 커뮤니티를 지원한다.
  • 또한 nginx plus와 같은 사용버전도 제공되며, 고급 기능 및 지원을 제공한다.

nginx 설치하기

  • 서버 환경
OS : CentOS Stream 8
Nginx : v1.14
  • NginX package를 다운 받아 설치하기 위해 Repository를 설정
sudo yum install yum-utils -y
  • NginX package를 다운 받아 설치하기 위해서는 Repository를 설정
# /etc/yum.repos.d/nginx.repo 생성하기
$ cat /etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=0
enabled=0
  • nginx mainline 설치
# nginx는 stable, mainline 두가지 버전이 존재하는 defailt 설치 방식으로는 stable이며, 버그 수정 혹은 보안 패치는 mainline에서 먼저 적용되며, stable 버전은 third-party 모듈을 사용하고 있기 때문에 신규 버전에서의 호환성 문제가 적다.
$ sudo yum-config-manager --enable nginx-mainline
  • nginx 설치
$ yum install nginx

# nginx version 확인
$ nginx -v
  • nginx 환경 설정
# 기본 환경 설정 파일은 /etc/nginx/nginx.conf 이다.
$ cd /etc/nginx/

nginx 설정하기

http 속성 nginx.conf 관련 내용 (/etc/nginx/nginx.conf)

  • nginx의 기본 설정 파일인 nginx.conf에서 설정을 확인 및 변경한다.
  1 # For more information on configuration, see:
  2 #   * Official English Documentation: http://nginx.org/en/docs/
  3 #   * Official Russian Documentation: http://nginx.org/ru/docs/
  4
  5 user nginx;
  6 worker_processes auto;
  7 error_log /var/log/nginx/error.log;
  8 pid /run/nginx.pid;
  9
 10 # Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
 11 include /usr/share/nginx/modules/*.conf;
 12
 13 events {
 14     worker_connections 1024;
 15 }
 16
 17 http {
 18     log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
 19                       '$status $body_bytes_sent "$http_referer" '
 20                       '"$http_user_agent" "$http_x_forwarded_for"';
 21
 22     access_log  /var/log/nginx/access.log  main;
 23
 24     sendfile            on;
 25     tcp_nopush          on;
 26     tcp_nodelay         on;
 27     keepalive_timeout   65;
 28     types_hash_max_size 2048;
 29
 30     include             /etc/nginx/mime.types;
 31     default_type        application/octet-stream;
 32
 33     # Load modular configuration files from the /etc/nginx/conf.d directory.
 34     # See http://nginx.org/en/docs/ngx_core_module.html#include
 35     # for more information.
 36     include /etc/nginx/conf.d/*.conf;
 37
 38     server {
 39         listen       80 default_server;
 40         listen       [::]:80 default_server;
 41         server_name  _;
 42         root         /usr/share/nginx/html;
 43
 44         # Load configuration files for the default server block.
 45         include /etc/nginx/default.d/*.conf;
 46
 47         location / {
 48         }
 49
 50         error_page 404 /404.html;
 51             location = /40x.html {
 52         }
 53
 54         error_page 500 502 503 504 /50x.html;
 55             location = /50x.html {
 56         }
 57     }
 58
 59 # Settings for a TLS enabled server.
 60 #
 61 #    server {
 62 #        listen       443 ssl http2 default_server;
 63 #        listen       [::]:443 ssl http2 default_server;
 64 #        server_name  _;
 65 #        root         /usr/share/nginx/html;
 66 #
 67 #        ssl_certificate "/etc/pki/nginx/server.crt";
 68 #        ssl_certificate_key "/etc/pki/nginx/private/server.key";
 69 #        ssl_session_cache shared:SSL:1m;
 70 #        ssl_session_timeout  10m;
 71 #        ssl_ciphers PROFILE=SYSTEM;
 72 #        ssl_prefer_server_ciphers on;
 73 #
 74 #        # Load configuration files for the default server block.
 75 #        include /etc/nginx/default.d/*.conf;
 76 #
 77 #        location / {
 78 #        }
 79 #
 80 #        error_page 404 /404.html;
 81 #            location = /40x.html {
 82 #        }
 83 #
 84 #        error_page 500 502 503 504 /50x.html;
 85 #            location = /50x.html {
 86 #        }
 87 #    }
 88
 89}
  • error_log -> nginx의 error log가 쌓이는 경로
  7 error_log /var/log/nginx/error.log;
  • pid -> nginx의 Process ID(PID)가 저장되는 경로
  8 pid /run/nginx.pid;
  • worker_connections -> wocker Process가 동시에 처리할 수 있는 접속자의 수를 나타낸다.
 13 events {
 14     worker_connections 1024;
 15 }
  • include -> 포함시킬 외부파일을 정의하며, mime.types는 파일에 작성된 내용들을 현재 파일로 가져온다.
# /usr/share/nginx/modules/*.conf 는 .conf로 끝나는 모든 파일을 포함시켜 가져온다.
 10 # Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
 11 include /usr/share/nginx/modules/*.conf;

30     include             /etc/nginx/mime.types;

 33     # Load modular configuration files from the /etc/nginx/conf.d directory.
 34     # See http://nginx.org/en/docs/ngx_core_module.html#include
 35     # for more information.
 36     include /etc/nginx/conf.d/*.conf;
  • default_type -> 웹서버의 기본 Content-Type을 정의
31     default_type        application/octet-stream;
  • log_format -> log 형식을 지정, 후술한 로그 형태에 따라 log가 작성되고 기록된다.
18     log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
 19                       '$status $body_bytes_sent "$http_referer" '
 20                       '"$http_user_agent" "$http_x_forwarded_for"';
  • access_log -> 접속 log가 쌓이는 경로
 22     access_log  /var/log/nginx/access.log  main;
  • sendfile() 함수의 사용 여부를 지정하며, 해당 부분은 한 파일의 디스크립터와 다른 파일의 디스크립터간에 데이터를 복사하는 것으로 커널 내부에서 복사가 진행된다.
 24     sendfile            on;
  • keepalive_timeout -> client에서 연결이 유지될 시간을 정의한다.
27     keepalive_timeout   65;

server 속성 default.conf 관련 내용(/etc/nginx/conf.d/default.conf)

  • default.conf는 nginx.conf를 통해 include된 서버 설정 관련 파일이며, default1.conf, default2.conf 등 여러 개의 파일을 추가하여 서버 관련한 설정을 추가로 만들어 포함시킬수 있다.
  • default.conf가 /etc/nginx/conf.d/ 경로에 존재하지 않을시 직접 생성한다.
  • nginx의 *.conf에 관한 내용

  • 개인적인 필자의 생각이지만, 해당 OS(centos8 stream)의 nginx 설치시 /etc/nginx/conf.d/default.conf가 존재하지 않고, default.conf의 내용이 nginx.conf에 포함되어 있었다.
  • 필자는 server 속성을 별도로 관리하기 위해, nginx.conf에 있는 server 부분을 모두 주석 처리하고 default.conf를 /etc/nginx/conf.d/ 경로에 직접 80,443을 위한 default.conf 각각 생성해 줄것이다.
  • nginx.conf에 대한 자세한 설명은 nginx.conf.default 파일에서 확인할 수 있다.

  • /etc/nginx/conf.d/default80.conf
# CentOS 8 Stream의 기본 Nginx 설치에서 /etc/nginx/conf.d/default.conf 파일은 일반적으로 제공되지 않기 때문에 직접 생성해주자.

# /etc/nginx/nginx.conf의 아래 부분을 복사 후 주석처리 하며, 
vim /etc/nginx/conf.d/default80.conf으로 생성
 38 #    server {
 39 #        listen       80 default_server;
 40 #        listen       [::]:80 default_server;
 41 #        server_name  _;
 42 #        root         /usr/share/nginx/html;
 43 #
 44 #        # Load configuration files for the default server block.
 45 #        include /etc/nginx/default.d/*.conf;
 46 #
 47 #        location / {
 48 #        }
 49 #
 50 #        error_page 404 /404.html;
 51 #            location = /40x.html {
 52 #        }
 53 #
 54 #        error_page 500 502 503 504 /50x.html;
 55 #            location = /50x.html {
 56 #        }
 57 #    }
# 주석 처리 방법은 주석 할 부분을 v로 선택후, : 입력 하고 norm i# 입력하고 엔터하면 주석처리 된다.
  • $ vi /etc/nginx/conf.d/default.conf 파일 생성 후 위 내용 복사
$ vim /etc/nginx/conf.d/default.conf
  1 server {
  2         listen       80 default_server;
  3         listen       [::]:80 default_server;
  4         server_name  _;
  5         root         /usr/share/nginx/html;
  6
  7         # Load configuration files for the default server block.
  8         include /etc/nginx/default.d/*.conf;
  9
 10         location / {
 11         }
 12
 13         error_page 404 /404.html;
 14             location = /40x.html {
 15         }
 16
 17         error_page 500 502 503 504 /50x.html;
 18             location = /50x.html {
 19         }
 20 }
  • nginx 재 시작 후 접속하기
$ sudo nginx -s stop
$ sudo nginx -s reload

nginx HTTPS 액세스 구성하기

  • /etc/nginx/nginx.conf에서 아래 부분을 복사후 /etc/nginx/conf.d/default443.conf 파일 생성후 복사
 61 #    server {
 62 #        listen       443 ssl http2 default_server;
 63 #        listen       [::]:443 ssl http2 default_server;
 64 #        server_name  _;
 65 #        root         /usr/share/nginx/html;
 66 #
 67 #        ssl_certificate "/etc/pki/nginx/server.crt";
 68 #        ssl_certificate_key "/etc/pki/nginx/private/server.key";
 69 #        ssl_session_cache shared:SSL:1m;
 70 #        ssl_session_timeout  10m;
 71 #        ssl_ciphers PROFILE=SYSTEM;
 72 #        ssl_prefer_server_ciphers on;
 73 #
 74 #        # Load configuration files for the default server block.
 75 #        include /etc/nginx/default.d/*.conf;
 76 #
 77 #        location / {
 78 #        }
 79 #
 80 #        error_page 404 /404.html;
 81 #            location = /40x.html {
 82 #        }
 83 #
 84 #        error_page 500 502 503 504 /50x.html;
 85 #            location = /50x.html {
 86 #        }
 87 #    }
  • /etc/nginx/conf.d/default443.conf 에 주석 처리된 부분은 편집기 접속후 v로 제거할 부분 선택, : 입력후 norm 1x 입력후 엔터하면 주석이 제거된다.
$ vim /etc/nginx/conf.d/default443.conf 
  1 server {
  2         listen       443 ssl http2 default_server;
  3         listen       [::]:443 ssl http2 default_server;
  4         server_name  _;
  5         root         /usr/share/nginx/html;
  6
  7         ssl_certificate "/etc/pki/nginx/server.crt";
  8         ssl_certificate_key "/etc/pki/nginx/private/server.key";
  9         ssl_session_cache shared:SSL:1m;
 10         ssl_session_timeout  10m;
 11         ssl_ciphers PROFILE=SYSTEM;
 12         ssl_prefer_server_ciphers on;
 13
 14         # Load configuration files for the default server block.
 15         include /etc/nginx/default.d/*.conf;
 16
 17         location / {
 18         }
 19
 20         error_page 404 /404.html;
 21             location = /40x.html {
 22         }
 23
 24         error_page 500 502 503 504 /50x.html;
 25             location = /50x.html {
 26         }
 27 }

nginx HTTPS 액세스 구성

  • Certification 파일 디렉터리 생성
$ cd /etc/nginx; sudo mkdir certs
  • CA Certificates 생성
# Root CA의 비밀키 생성
$ openssl genrsa -out ca.key 4096

# 공개키 생성
$ openssl req -x509 -new -nodes -sha512 -days 365 \
-key ca.key \
-out ca.crt
  • nginx Certificates 생성
# nginx의 비밀키 생성
$ openssl genrsa -out nginx.key 4096

# nginx의 CSR 파일 생성
$ openssl req -sha512 -new \
-key nginx.key \
-out nginx.csr
  • x509 v3 확장 파일을 생성
# nginx 호스트에 연결하기 위해 FQDN 또는 IP 주소를 사용하는지 여부에 관계없이 SAN(주체 대체 이름) 및 x509 v3을 준수하는 nginx 호스트에 대한 인증서를 생성할 수 있도록 이 파일을 생성
$ cat > v3.ext <<-EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names

[alt_names]
IP.1=192.168.60.239
EOF

# 위 작업 수행 이후, SAN 등록하는 작업 수행
$ openssl x509 -req -sha512 -days 365 \
-extfile v3.ext \
-CA ca.crt -CAkey ca.key -CAcreateserial \
-in nginx.csr \
-out nginx.crt
  • vim /etc/nginx/conf.d/default443.conf 의 7,8 라인 인증서 키 경로 변경
  7         ssl_certificate "/etc/nginx/certs/nginx.crt";
  8         ssl_certificate_key "/etc/nginx/certs/nginx.key";
  • nginx 재 시작 후 접속하기
$ sudo nginx -s stop
$ sudo systemctl restart nginx
$ sudo nginx -s reload

0개의 댓글