Nginx 기본 사용법

SummerToday·2024년 3월 5일

도커, 서버 기술

목록 보기
23/34
post-thumbnail

Nginx 설치

docker run -dit -p 80:8080 --name myos ubuntu:20.04
docker exec -it myos /bin/bash

apt-get update
apt-get install nginx

apt-get install vim

nginx.conf

cf. find -name nginx.conf 명령어를 통해 nginx.conf 파일의 위치를 찾는다.
bc. 버전마다 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;
        tcp_nodelay on;
        keepalive_timeout 65;
        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_ciphers on;

        ##
        # 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;
#       }
#}

  • nginx의 기본 설정 파일이다.

  • 크게 user, worker_processes, pid, include, events, http 부분으로 이루어져 있다.

    c. # : 주석

    • user
      Nginx 워커 프로세스가 실행될 사용자를 지정한다.
      보통은 www-data로 설정한다.

    • worker_processes
      이 디렉티브는 Nginx가 실행할 워커 프로세스의 수를 지정한다.
      보통은 auto로 설정한다.

    • pid
      Nginx 마스터 프로세스의 PID(Process ID : 실행 중인 각 프로세스에 할당인 고유한 식별자) 파일을 지정한다.
      /var/run/nginx.pid와 같은 경로에 위치하며, Nginx 프로세스의 PID를 추적하는 데 사용된다.

    • include
      외부에서 참조할 파일들을 설정한다.

    • events
      Nginx의 이벤트 처리 방식을 설정한다. 보통 기본 설정 값을 그대로 사용한다.

      • worker_connections
        각 워커 프로세스가 처리할 수 있는 동시 연결 수를 설정한다.
        해당 값은 시스템의 리소스 및 서버의 예상 트래픽에 따라 조정된다.

      • use
        이벤트 처리 메커니즘을 지정한다.
        ex. epoll, kqueue, eventport, select

    • http
      HTTP 서버의 설정 부분이다.

      cf. /etc/nginx/conf.d/mysite.com.conf 형태로 웹 서비스별 설정을 별도의 파일로 할 수 있다.

      cf. /etc/nginx/sites-enabled 폴더가 include 되어 있는데, 해당 폴더의 default 파일은 /etcnginx/sites-available 폴더의 default 파일을 가리키는 심볼릭 링크이다.

      따라서 /etc/nginx/sites-available/default 파일의 설정을 변경한 후 nginx를 재실행하면 자동으로 /etc/nginx/sites-enabled/default에 반영되는 것이다.


/etc/nginx/sites-available/default 파일 server 설정

server {
        listen 8080 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 /blog {
                root/var/www;
        } 
        
        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:/var/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;
        #}
}
  • listen
    HTTP 요청을 받을 포트를 설정한다.
    cf. [::]는 모든 IPv6 주소를 나타낸다.
    listen 8080 default_server;
     listen [::]:80 default_server; # IPv6 설정

  • default_server
    모든 웹 서버 요청을 받는다는 의미이다.

  • root
    웹 서버의 루트 디렉토리를 지정한다. 여기서는 기본으로 /var/www/html로 설정되어 있다.

    예를 들어, 웹 서버의 루트 디렉토리가 /var/www/html로 설정되어 있다면, 클라이언트가 http://example.com/index.html에 접속하면 서버는 /var/www/html/index.html 파일을 찾아 제공한다.

    cf. 해당 파일의 설정에서는 서버에게 별도의 파일 요청 없이 요청시 제공되는 기본 html 파일은 index.html index.htm index.nginx-debian.html이다. 예를들어, index.html이 없으면 index.htm이 index.htm도 없으면 index.nginx-debian.html이 호출된다.

  • server_name
    요청을 받을 도메인 이름을 설정한다.

    server_name _; # 도메인 이름이 없을 시 _(언더바)로 기입.
     or
     server_name example.org www.example.org; # 도메인 이름이 존재 시 이와 같이 순차적으로 기입.
    

  • location
    요청된 URI(의 / 이하 경로)에 따라 처리 방법을 지정한다. ex. 12.123.111.122/blog/index.html
    해당 설정에서는 URI에 해당하는 파일 또는 디렉토리가 없을 경우 404 오류를 반환한다.

    location / {
    try_files $uri $uri/ =404; # 기본 설정
    } # 12.123.111.122/aaa/example.html 요청 시 /var/www/html/aaa/example.html로 매칭된다.


    location /blog {
    root /var/www;
    } # 12.123.111.122/blog/example.html 요청 시 /var/www/blog/example.html로 매칭된다.

    • try_files file1 [file2 ...] fallback;
      여러 개의 파일 또는 디렉토리를 찾는데 사용되는 지시어이다. 그 중에 하나를 반환하거나, 찾을 수 없는 경우에는 지정된 오류 코드(fallback)를 반환한다.

    • $uri: 요청된 URI에 해당하는 파일을 찾는다.

    • $uri/: 요청된 URI에 해당하는 디렉토리를 찾는다.

    • =404: 찾을 수 없는 경우, 즉 요청된 파일 또는 디렉토리가 없는 경우, 클라이언트에게 404 오류를 반환한다.

  • cf. 해당 파일의 설정을 변경한 후에는 서버를 재부팅 해줘야 변경사항들이 적용이 된다.

    $ service nginx restart

  • cf. http://43.200.185.78/blog/와 http://43.200.185.78/blog 차이

    • http://43.200.185.78/blog/ 같이 슬래시('/')가 있는 경우, 이것은 일반적으로 디렉토리를 나타낸다. 서버는 이 요청을 받으면 /flask/ 디렉토리 내의 기본 파일(예: index.html)을 찾는다.

    • http://43.200.185.78/blog 같이 슬래시('/')가 없는 경우, 이것은 일반적으로 파일이나 루트 URI를 나타낸다. 서버는 이 요청을 받으면 정확한 파일을 찾게된다.




해당 글은 다음 강의의 내용을 참고한 글임을 밝힙니다. 자세한 내용은 다음 강의에서 확인해볼 수 있습니다.
인프런, 잔재미 코딩, ⌜풀스택을 위한 도커와 최신 서버 기술(리눅스, nginx, AWS, HTTPS, flask 배포) [풀스택 Part3]⌟
profile
블로그 이관했습니다.

0개의 댓글