Devops/웹 서버 관리

Nginx - 설치와 conf, default 파일 설정 방법

settong 2024. 9. 4. 16:06
반응형

Nginx란?

  1. 정적 파일들을 처리하기 위해 사용되는 http server
  2. reverse proxy server 역할. 80번 포트로 들어오는 내용을 다른 포트로 분산시켜주기가 가능함!!
  • 비동기 이벤트 구조를 기반으로 동작한다.
  • Event-Driven 방식:
    • 서버로 들어오는 connection 들을 Event-Handler를 통해 비동기 방식으로 처리
    • 이러한 방식으로 인해 적은 메모리로 서버를 운영할 수 있음.
    • 싱글스레드
    • cpu가 관여하지 않는 작업(scker read / wirter, I/O 등)을 진행할 때는 기다리지않고 다른 작업 수행하고, 진행중이라면 작업이 종료되면 이벤트가 발생하면서 그 다음 작업 처리를 시작한다.

 

 

 


Nginx 설치

Linux 서버에서 Nginx 설치하기

 

1. apt-get(패키지 관리 명령어 도구) 업데이트

sudo apt-get update

 

2. nginx 설치

sudo apt-get install nginx

 

 

 

 

 


nginx.conf 파일 설정

/etc/nginx/nginx.conf 전체

더보기

 

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
        worker_connections 768;
        # multi_accept on;
}

http {

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        types_hash_max_size 2048;
        # server_tokens off;

        # server_names_hash_bucket_size 64;
        # server_name_in_redirect off;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # SSL Settings
        ##

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_cipher

        ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        ##
        # Gzip Settings
        ##

        gzip on;

        # gzip_vary on;
        # gzip_proxied any;
        # gzip_comp_level 6;
        # gzip_buffers 16 8k;
        # gzip_http_version 1.1;
        # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}

#mail {
#       # See sample authentication script at:
#       # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#       # auth_http localhost/auth.php;
#       # pop3_capabilities "TOP" "USER";
#       # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#       server {
#               listen     localhost:110;
#               protocol   pop3;
#               proxy      on;
#       }
#
#       server {
#               listen     localhost:143;
#               protocol   imap;
#               proxy      on;
#       }
#}

 

core 설정

user www-data;
  • 워커프로세스의 권한을 지정해주는 구문이다.
  • user root;로 되어있으면 root권한으로 워커프로세스를 동작하므로 지양.
  • 또한 일반 유저의 권한으로 쉘에 접속할 수 없어야 안전.
worker_processes auto;
  • worker_processes 는 워커프로세스를 몇개 생성할 것인지 지정.
  • 물리적인 코어 개수만큼 할당하는 것이 이상적. auto로 하면 자동으로 cpu 개수에 알맞게 프로세스 생성.
  • 코어 10~20% 를 남겨두고 할당하는것도 운영체제를 위해 권장.
pid /run/nginx.pid;
  • nginx.pid 파일 경로. nginx.pid 파일은 nginx 마스터 프로세스 id 정보 저장됨.
include /etc/nginx/modules-enabled/*.conf;
  • include 지시어 뒤의 파일 내용을 포함하는 기능을 수행함.
  • conf파일 내용을 포함하겠다는 뜻.

 

 

events 블록 설정

events 블록은 네트워크 작동 환경을 설정하는 지시어를 제공.

worker_connections 768;
  • 하나의 워커프로세스가 동시에 처리할수 있는 접속 수를 정의.
  • 최대 처리 접속 수 는 worker_connections * worker_processes
multi_accept on;
  • on/off 로 활성화/비활성화 될 수 있으며, default는 off.
  • 워커프로세스가 한번에 하나의 새 연결을 승인. on 일 경우 워커프로세스는 한번에 모든 새 연결을 수락함.

 

 

http 블록 설정

하위에 server블록, location 블록을 갖는 루트블록으로, 여기서 선언된 값은 하위 블록에 상속되어 서버의 기본값이 됨.

- Basic Setting (바로가기)

sendfile on;
tcp_nopush on;
types_hash_max_size 2048;
# server_tokens off;

# server_names_hash_bucket_size 64;
# server_name_in_redirect off;

include /etc/nginx/mime.types;
default_type application/octet-stream;
  • sendfile : nginx에서 정적 파일을 보내도록 활성(on) / 비활성(off)
  • tcp_nopush : 클라이언트에게 패킷 전송하기 전, 버퍼가 가득찼는지 확인하고 다 찼으면 패킷을 전송하도록 하여 네트워크 오버헤드를 줄이도록 설정(on) / 비활성(off)
  • types_hash_max_size : type 해시 테이블의 최대 사이즈 설정.
  • server_tokens : 오류페이지에서 “Server” response 헤더필드에 nginx 버전을 내보냄. on|off|build|string값이 올 수 있고 string 의 경우 1.9.13v 이후부터 사용가능하며, 빈 문자열은 불가능하다.
  • server_names_hash_bucket_size : 서버 호스트 네임의 해시 버킷 사이즈 설정. 기본값은 프로세서의 캐시에 따라 달라짐.
  • server_name_in_redirect : nginx에서의 server_name 지시어로 지정된 기본 server name 사용을 활성화/비활성화한다. 기본 server name을 사용할 수 없는 경우 “Host” request 헤더 필드의 이름이 사용된다. 없으면 서버의 IP 주소가 사용된다.
  • default_type : 웹 서버의 기본 Content-Type을 설정. octet-stream은 바이너리 형태의 타입을 의미. nginx에서 해석할 수 없는 type일 경우 요청을 기본 type으로 받음

- SSL Setting (바로가기)

OpenSSL 라이브러리가 필요,

ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_cipher
  • ssl_protocols : 지정된 프로토콜 활성화
  • ssl_prefer_server_cipher : SSLv3 및 TLS 프로토콜을 사용할 때 server 암호가 클라이언트 암호보다 선호되도록 지정함. on|off로 지정할 수 있고 defualt는 off.

- Logging Settings (바로가기)

로그저장에 대한 설정

access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
  • 엑세스 로그와 에러 로그를 저장할 파일 설정

- Gzip Settings (바로가기)

gzip 방식을 사용하여 response를 압축하기 위한 설정.

gzip on;

# gzip_vary on;
# gzip_proxied any;
# gzip_comp_level 6;
# gzip_buffers 16 8k;
# gzip_http_version 1.1;
# gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
  • gzip : 전송 내용을 gzip으로 압축 on|off
  • gzip_vary : gzip | gzip_static | gunzip 이 “on”인 경우 “Vary: Accept-Encoding” response 헤더 필드 삽입을 on | off
  • gzip_proxied : request/response 에 따랄 프록시 request에 대한 응답의 gzip압축을 활성화 하거나, 비활성화 함. 요청이 프록시 되는 것은 request의 “Via” 헤더 필드가 존재하는지에 따라 결정됨.
    • any : 프록시된 모든 request에 대해 압축 활성화
    • off : 프록시된 모든 request에 대해 압축 비활성화, 매개변수 무시
    • expired : response헤더에 “Expires”필드가 포함된 경우 압축 활성화
    • no-cache : response헤더에 “no-cache” 파라미터가 포함된 “Cache-Control”필드가 있는경우 압축 활성화
    • private : response헤더에 “private” 파라미터가 포함된 “Cache-Control”필드가 있는경우 압축 활성화
    • no_last_modified : response헤더에 “Last-Modified”필드가 포함되지 않은 경우 압축 활성화
    • no_etag : response헤더에 “ETag”필드가 포함되지 않은 경우 압축 활성화
    • auth : response헤더에 “Authorization”필드가 포함된 경우 압축 활성화
  • gzip_comp_level : response level의 gzip 압축을 설정. level은 1~9까지 있음
  • gzip_buffers : response 압축에 필요한 buffer 사이즈 설정. 기본적으로 buffer 사이즈는 하나의 메모리 페이지와 같으며, 플랫폼에 따라 4K~8K
  • gzip_http_version : response 압축에 필요한 request의 http 최소 버전
  • gzip_types : 지정된 type에 대해 response 압축을 활성화함. " text/html" 유형의 응답은 항상 압축됨.

- Virtual Host Configs

include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;

 

 

 

 

 

 


default 파일 설정

nginx.conf 를 통해 include 될 server( & location) 블록을 설정할 수 있다.

server 블록은 웹사이트 하나를 선언함. sever블록이 여러개이면 하나의 host에서 여러 웹사이트를 서빙할 수 있다.

 

1. nginx에게 request가 오면

2. http 헤더의 Host부분을 통해 request 가 어느 도메인(or IP)로 가야하는 확인하고

3. 해당 virtual host(= server)로 보낸다.

 

즉, 이를 통해 가상으로 호스트가 여러개인척 가능

 

/etc/nginx/sites-available/default 전체

더보기
# https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/
# https://wiki.debian.org/Nginx/DirectoryStructure
#
# In most cases, administrators will remove this file from sites-enabled/ and
# leave it as reference inside of sites-available where it will continue to be
# updated by the nginx packaging team.
#
# This file will automatically load configuration files provided by other
# applications, such as Drupal or Wordpress. These applications will be made
# available underneath a path with that package name, such as /drupal8.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# Default server configuration
#
server {
        listen 80 default_server;
        listen [::]:80 default_server;

        # SSL configuration
        #
        # listen 443 ssl default_server;
        # listen [::]:443 ssl default_server;
        #
        # Note: You should disable gzip for SSL traffic.
        # See: https://bugs.debian.org/773332
        #
        # Read up on ssl_ciphers to ensure a secure configuration.
        # See: https://bugs.debian.org/765782
        #
        # Self signed certs generated by the ssl-cert package
        # Don't use them in a production server!
        #
        # include snippets/snakeoil.conf;

        root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name _;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

        # pass PHP scripts to FastCGI server
        #
        #location ~ \.php$ {
        #       include snippets/fastcgi-php.conf;
        #
        #       # With php-fpm (or other unix sockets):
        #       fastcgi_pass unix:/run/php/php7.4-fpm.sock;
        #       # With php-cgi (or other tcp sockets):
        #       fastcgi_pass 127.0.0.1:9000;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #       deny all;
        #}
}


# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#       listen 80;
#       listen [::]:80;
#
#       server_name example.com;
#
#       root /var/www/example.com;
#       index index.html;
#
#       location / {
#               try_files $uri $uri/ =404;
#       }
#}
listen 80 default_server;
listen [::]:80 default_server;

server_name _;

(바로가기)

  • listen 이후 명시한 포트로 들어오는 요청을 server 블록의 내용으로 처리하겠다는 뜻
  • default_server를 default port의 의미로 이해하면 됨.
    default_server가 없으면 가장 먼저 정의된 server가 default_server가 됨.
  • 80 은 http port 로 https 의 경우 443 으로 설정해주면 됨.
    (하지만, aws에서 LB 설정시 80port → 443port로 리스너를 설정했다면 80으로 둬도 됨.)
  • 도메인 연결 시 server_name 설정 할 때 www. 도 추가해주기.
  • ex(server_name test.com www.test.com)
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
  • root로 경로설정하고, root에 있는 index 파일들로 접근하겠다는 의미.
  • root 는 server 블록 내에 명시해야함. http 블록에 명시하면 동작 안한다.
    location 내에서도 동작하는데 location 밖, server 내에 명시하면 server내 모든 location에 경로가 적용된다.
  • root 의 defulat 경로인 /var/www/html 의 권한은 755이다.
    ❗️root 바꿔 줄 경우 해당 폴더 권한이 755인지 꼭 확인하기. others 권한이 막혀있으면 404 error 뜸.
location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
}

server블록 내에서 특정 server의 url 을 처리하는데 사용한다.

  • location [경로] {...} 로 블록 구성된다. (바로가기)
    • 경로부분 문법에 따라 일치할 시에 동작한다.
      : “~*”는 대소문자를 구분하지 않는 기호
      : “$”는 끝나는 기호
      : “^”는 시작기호
      : “~”는 대소문자를 구분하는 기호
      • 1순위 : location = /[패턴] {...} : 정확하게 일치할 시 (정규식 사용 금지)
        [경로]?parameter 는 가능하지만 [패턴]/[패턴]+문자열은 불가능
      • 2순위 : location ^~ /[패턴] {...} : 해당 패턴으로 시작할 시
      • 3순위 : location ~ /[패턴] {...} : 대소문자 구분하여 일치할 시
      • 4순위 : location ~* /[패턴] {...} : 대소문자 구분하지 않고 일치할 시
      • location /[패턴] {...} : 해당 패턴 하위 일치
        [패턴]?parameter[패턴]/  [패턴]+문자열… 가능
      • try_files path1 … final; 앞의 path 부터 검색하고, 파일을 찾게되면 그 파일 반환. 못찾으면 마지막 명시된 파일 반환. 앞의 모든 path가 존재하지 않으면 final이 존재하지 않더라도 rewrite 된다.
  • try_files (바로가기)
    파일 → 디렉토리 순으로 path 입력
    1. try_files path1 … final;
      앞의 path 부터 검색하고, 파일을 찾게되면 그 파일 반환.
      못찾으면 마지막 명시된 파일 반환.
      앞의 모든 path가 존재하지 않으면 final이 존재하지 않더라도 rewrite 된다.
    2. try_files path1 … =code;
      앞의 path 부터 검색하고 파일 찾게되면 그 파일 반환.
      못찾으면 code 반환.
❗ React Dom Router 를 쓰는 경우 → SPA
index.html 파일 하나만 쓰므로
try_files $uri $uri/ /index.html;로 적용해야함.
: $uri 확인 → $uri 경로 내 확인 → index.html 반환.
#location ~ \\.php$ {
#       include snippets/fastcgi-php.conf;
#
#       # With php-fpm (or other unix sockets):
#       fastcgi_pass unix:/run/php/php7.4-fpm.sock;
#       # With php-cgi (or other tcp sockets):
#       fastcgi_pass 127.0.0.1:9000;
#}

❗️해당 주석 안풀면 .php 파일로 접근 시 .php 파일이 다운로드 됨. 주석만 풀면 502 error…

  • index에 index.php 추가해주기
  • sudo apt-get install php 명령어로 php 설치
  • /var/run/php 경로로 이동해서, php-fpm.sock 파일 버전 확인
  • include, fastcgi_pass 지시어 주석 풀어주기.
  • fastcgi_pass 의 php-fpm.sock 경로, 버전 잘 확인하여 수정.
  • fastcgi_index [파일명] 지시어를 추가하여 초기 php 지정할 수 있음.
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\\.ht {
#       deny all;
#}
  • root 에 apach 문서가 있을 시 .ht 파일 비활성화…

 

 

728x90
반응형