[ 살펴보기 ] Ngnix - HTTP Module
![[ 살펴보기 ] Ngnix - HTTP Module](https://cdn.hashnode.com/res/hashnode/image/upload/v1727280914240/783d33fd-db44-45dc-8eb5-bb2ea3e63a65.jpeg)
이전 포스트에선 core module, event module과 함께 http 요청에 html 파일을 response하는 간단한 세팅을 살펴보았다. 이번 포스트에선 http server를 구성할 때 사용되는 http module에 대해 좀 더 살펴본다. 우선 http module을 이루는 http, server, location block부터 시작하자.
예제는 Ubuntu 22.04 환경에서 진행되었고 nginx는 apt를 통해 설치되었다.
Http block
Nginx configuration 파일의 root level에 선언되며 http와 관련된 block이나 directive를 선언할 수 있는 block이다.
nginx.conf 파일을 살펴보면 아래와 같이 http block이 선언되어 있는 것을 확인할 수 있다. http block 아래 server block을 추가해 site hosting 관련 설정을 한다. 아래의 예제에서는 /etc/nginx/sites-enabled 폴더에 있는 모든 server 관련 설정을 include하고 있다.
...
http {
...
include /etc/nginx/sites-enabled/*;
}
만약 sites-enabled 폴더에 default 파일 하나만 존재하고 default 파일에서 server block을 아래와 같이 설정하고 있다면
server {
listen 80;
listen [::]:80;
root /home/user/test-nginx-static;
index index.html;
server_name mytest.com;
location / {
try_files $uri $uri/ =404;
}
}
위의 http block은 다음과 같은 의미다.
...
http {
...
server {
listen 80;
listen [::]:80;
root /home/user/test-nginx-static;
index index.html;
server_name mytest.com;
location / {
try_files $uri $uri/ =404;
}
}
}
위의 예제처럼 default nginx.conf 파일에 server block을 직접 추가하는 것 보다 서로 다른 server block을 각각의 설정 파일로 생성하여 sites-available 폴더에 추가하고 해당 설정 파일의 symlink를 sites-enabled 폴더에 생성해서 관리하는 방법이 있다.
예를 들어 다음과 같은 server block을 설정하는 example이라는 설정 파일을 /etc/nginx/site-available 경로에 생성했다고 가정하자.
# /etc/nginx/site-available/example
server {
listen 80;
listen [::]:80;
root /home/user/example;
index index.html;
server_name example.com;
location / {
try_files $uri $uri/ =404;
}
}
위의 설정 파일을 생성하고 다음 명령어를 통해 /etc/nginx/site-enabled 경로에 symlink를 생성한다.
sudo ln -s /etc/nginx/sites-available/example /etc/nginx/sites-enabled/
이제 /etc/nginx/site-enabled의 파일 목록을 조회해 보면 example 설정 파일에 대한 symlink가 생성된 것을 확인할 수 있다. site-enabled 경로에 있는 example은 synlimk이므로 이후에 example server block에 수정이 필요하면 site-available 경로에 있는 example 파일을 수정해주면 된다.
이제 처음 예제에서 보았듯이 http block에서 site-enabled 경로에 있는 모든 파일을 include 해준다.
...
http {
...
include /etc/nginx/sites-enabled/*;
}
마지막으로 다음 명령어를 통해 configuration 수정 내용을 적용해준다.
sudo systemctl reload nginx;
configuration 파일을 수정할 때 오타나 syntax error가 존재한다면 nginx service가 다운될 수 있으므로 configuration 파일을 수정하면 다음 명령어를 통해 이상이 없는지 체크할 수 있다.
sudo nginx -t
Server block
server block을 통해 site hosting에 대한 설정을 할 수 있다. 예를 들어 mytest.com 이라는 사이트와 yourtest.com 이라는 사이트 두 개를 운영 중이라면 server block을 별개로 나누어 두 사이트를 hosting한다. 그 뿐만 아니라 proxy_pass directive를 통해 request를 뒤에서 운영 중인 application으로 전달해 reverse-proxy로 사용할 수도 있다.
다음 예제를 살펴보자.
server {
listen 80;
listen [::]:80;
root /home/user/test-nginx-static;
index index.html;
server_name mytest.com;
location / {
try_files $uri $uri/ =404;
}
}
만약 mytest.com이라는 도메인을 구매해 현재 운영중인 server ip와 a record를 통해 연결했다고 가정해보자. 위의 server block은 client가 mytest.com으로 request를 보내면 /home/user/test-nginx-static 경로에 있는 index.html을 response로 전달해준다.
Server block에서 사용할 수 있는 directive는 다양하다. 모든 directive list는 documentation을 통해 확인할 수 있다. ( Documentation directive 정보 중 context에 server가 포함된 directive가 server block에서 사용 가능한 directive다 )
Location block
Location block을 통해 server block안에서 어떤 request path를 catch하여 새로운 구성을 적용할 것인지 설정할 수 있다.
다음 예제를 살펴보자
server {
listen 80;
listen [::]:80;
root /home/user/mytest;
index index.html;
server_name mytest.com;
error_page 404 /error-page/not_found.html;
location /test/ {
error_page 404 mytest.com;
}
}
위의 설정을 기준으로 만약 mytest.com/paa와 같이 존재하지 않는 파일을 요청하면 404 status code와 not_found.html 파일이 응답으로 전달된다.
하지만 url이 mytest.com/test로 시작하는 요청은 /test/ location으로 구성한 block을 통해 처리되고 만약 mytest.com/test/ppa와 같이 존재하지 않는 파일을 요청하면 404 status code 대신 mytest.com으로 redirection 응답을 전달한다.
Location block에서 사용할 수 있는 directive는 다양하다. 모든 directive list는 documentation을 통해 확인할 수 있다. ( Documentation에서 directive 정보 중 context에 location이 포함된 directive가 location block에서 사용 가능한 directive다 )
위의 예제를 통해 http module을 구성하는 http, server, location block을 살펴보았다. http module에서 설정할 수 있는 directive는 http, server, location 모든 범위에서 설정할 수 있는 directive도 있는 반면 그렇지 않은 directive도 있다. 이제부터 기능 category별로 directive를 구분해서 살펴보자.
Host 세팅 관련
listen : listen하고 있을 port를 설정한다. listen할 port 다음 추가 option을 설정할 수도 있다.
default_server 옵션을 설정하면 listen에 설정한 port로 request가 전달되었을 때 해당 server block을 default로 사용하고 ssl option을 사용하면 해당 server block은 SSL을 통해 통신한다는 것을 명시한다.
server block에서 설정할 수 있다.server { listen 80 default_server; ... } server { listen 443 ssl; ... }server_name : catch할 hostname을 설정한다. nginx가 http request를 받으면 request의 host 정보와 server_name directive에 설정한 hostname을 비교하고 동일한 server_name이 있으면 해당 server block에 설정한 내용이 사용된다. 만약 아래와 같이 server block이 구성되어 있을 때 yourtest.com url를 통해 들어온 요청은 server_name yourtest.com server block을 통해 처리된다.
... server { listen 80; listen [::]:80; root /home/user/mytest; index index.html; server_name mytest.com; } server { listen 80; listen [::]:80; root /home/user/yourtest; index index.html; server_name yourtest.com; }아래의 예제와 같이 server_name은 하나만 선언하거나 복수로 선언할 수도 있고 wildcard(*)를 사용할 수도 있다.
server block에서 설정할 수 있다.server_name mytest.com; server_name www.mytest.com mytest.com; server_name *.mytest.com;reset_timedout_connection : on으로 설정되었을 때 client connection이 times out 되어 종료되었을 때 상태에 따라 memory에 남아 있을 수 있는 request 관련 정보를 삭제한다. default는 off이며 server block 뿐만 아니라 http, location block에서도 설정할 수 있다. ( 설정 가능한 값은 off 또는 on이다 )
http, server, location block에서 설정할 수 있다.reset_timedout_connection off | on;root : server block의 root directory를 설정한다. 예를들어 아래 server block의 root은 /home/user/mytest directory이므로 client가 http://mytest.com/order으로 request를 전달하면 nginx는 /home/user/mytest/order 폴더에 있는 index.html 파일을 response로 전달된다.
http, server, location block에서 설정할 수 있다.server { listen 80; listen [::]:80; root /home/user/mytest; index index.html; server_name mytest.com; }error_page : error status code에 따라 reponse로 전달할 file을 직접 설정할 수 있다. 만약 다음과 같이 error_page를 설정하면 해당 server block에서 발생하는 404 status code의 response는 nginx default 404 page가 아닌 /error-page/not_found.html 파일이 사용된다.
http, server, location block에서 설정할 수 있다.server { listen 80; listen [::]:80; root /home/user/mytest; index index.html; server_name mytest.com; error_page 404 /error-page/not_found.html; }error_page directive의 경로는 server block의 root 경로 기준 relative path로 설정해준다. 만약 존재하지 않는 페이지에 접근시 root index로 대체하고 status code 역시 200으로 변경해서 response하고 싶으면 다음과 같이 설정할 수 있다.
server { listen 80; listen [::]:80; root /home/user/mytest; index index.html; server_name mytest.com; error_page 404 =200 /index.html; }만약 404 response를 완전히 다른 url로 redirection 시키고 싶을 때는 다음과 같이 설정할 수 있다.
server { listen 80; listen [::]:80; root /home/user/mytest; index index.html; server_name mytest.com; error_page 404 mytest.com; }위와 같이 url을 통해 redirect이 발생하면 status code는 default로 302가 사용된다. 만약 redirect시 다른 redirect status code를 설정하고 싶다면 다음과 같이 설정한다.
server { listen 80; listen [::]:80; root /home/user/mytest; index index.html; server_name mytest.com; error_page 404 =301 mytest.com; }index : request url에 요청 파일의 정보가 포함되지 않았을 때 default로 전달할 파일을 설정한다. 예를들어 아래와 같이 설정하면 client가 mytest.com url로 request를 보냈을 때 index.html 파일이 index page로 전달된다.
server { listen 80; listen [::]:80; root /home/user/mytest; index index.html; server_name mytest.com; }아래와 같이 여러 파일이 설정되면 각 순서마다 파일이 존재하는지 확인하고 존재한다면 해당 파일을 response로 전달한다. 확인하는 순서는 정의한 순서를 따른다. 아래 예제 기준으로 index.html을 먼저 확인하고 존재하면 index.html이 전달된다. 만약 index directive에 설정된 파일이 모두 존재하지 않으면 403 error page가 전달된다.
http, server, location block에서 설정할 수 있다.index index.html index.phptry_files : request 응답을 위한 files을 찾을 때 try_files directive를 통해 여러 후보를 설정할 수 있다. 아래 예제와 같이 설정하면 http://mytest.com/order uri로 request가 들어오면 nginx는 먼저 order라는 이름의 파일이 있는지 확인하고 없으면 order.html이라는 이름의 파일이 있는지 확인한다. response로 전달한다. $uri는 request uri 정보를 담고 있는 nginx 변수다.
$uri/형식으로 설정해주는 이유는 order파일이 없으면 order라는 directory가 있는지 확인하고 만약 order directory에 index 파일이 있다면 해당 파일이 응답으로 return된다. 마지막 부분은 모든 파일을 찾지 못했을 때 어떤 status code로 응답할지 설정한다. 아무 status code도 설정하지 않으면 500 status code가 응답된다.http, server, location block에서 설정할 수 있다.server { ... root /home/user/mytest; server_name mytest.com; location / { try_files $uri $uri/ $uri.html =404; } }alias : 특정 location으로 들어온 request의 응답으로 전달할 파일의 위치를 server block과는 다른 위치로 새로 정의할 수 있다. 만약 /test/ location에 대한 alias를
/home/user/mytest/about/으로 설정하면 client가 mytest.com/test url을 통해 request를 보냈을 때/home/user/mytest/about/경로에 있는 index.html가 response로 전달되고 mytest.com/test/flower.jpg url을 통해 request를 보냈을 때/home/user/mytest/about/경로에 있는 flower.jpg 파일이 response로 전달된다.location block에서 설정할 수 있다.server { listen 80; listen [::]:80; root /home/user/mytest; index index.html; server_name mytest.com; location /test/ { alias /home/user/mytest/about/; } }
Request 관련 설정
client_max_body_size : client가 body를 포함한 request를 보낼 때 허용하는 최대 body 크기를 설정한다. 만약 request body의 크기가 설정 값 보다 크면 413 status code를 반환한다.
http, server, location block에서 설정할 수 있으며 default 값은 1mb다.client_max_body_size 1mclient_body_in_file_only : request의 body 내용을 file에 저장할 것인지 설정한다. default는 off이며 ( file에 저장하지 않는다 ) clean 또는 on으로 설정할 수 있다. clean으로 설정하면 request가 처리되고 난 이후에 body 정보를 저장한 file은 삭제된다.
http, server, location block에서 설정할 수 있다.client_body_in_file_only offclient_body_temp_path : request body 정보가 저장될 file을 생성할 경로를 설정한다.
http, server, location block에서 설정할 수 있다.lingering_close : client connection 어떻게 close할지 설정한다. default는 on이며 on으로 설정되면 linger_timeout directive에 설정된 시간만큼 connection을 유지하며 추가 request가 들어오면 처리한다. 설정 가능한 값은 on, off, always이며 특수한 경우가 아니라면 off로 설정하진 않는다.
http, server, location block에서 설정할 수 있고 만약 HTTP/2 connection에 대한 설정은server block에서 설정해야 한다.lingering_close onlingering_timeout : linger_close가 적용되고 있을 때 reqeust connection을 닫기 전까지 유지하는 시간을 설정한다. default는 5초이며
http, server, location block에서 설정할 수 있다.lingering_timeout 5max_ranges : partial content request에 대해 응답할 때 응답할 수 있는 최대 byte 범위를 정한다. default로 설정된 범위는 없으며
http, server, location block에서 설정할 수 있다.
MIME type 관련 설정
default_type : nginx.conf 파일은 다음과 같이 default로 mime.types 파일을 include한다.
include mime.types;그리고 mime.types 파일의 내용은 대략 다음과 같다.
types { text/html html htm shtml; text/css css; text/xml xml; image/gif gif; image/jpeg jpeg jpg; application/javascript js; application/atom+xml atom; application/rss+xml rss; text/mathml mml; text/plain txt; text/vnd.sun.j2me.app-descriptor jad; text/vnd.wap.wml wml; text/x-component htc; image/png png; image/tiff tif tiff; image/vnd.wap.wbmp wbmp; image/x-icon ico; image/x-jng jng; image/x-ms-bmp bmp; image/svg+xml svg svgz; image/webp webp; application/font-woff woff; application/java-archive jar war ear; application/json json; application/mac-binhex40 hqx; application/msword doc; ... }위의 예제를 통해 볼 수 있듯이 mime.types 파일은 types block을 통해 대부분의 mime type을 선언하고 있다. nginx는 client request에 응답으로 파일을 전달할 때 파일의 extension을 기준으로 mime type을 정해서 header의 Content-Type을 설정 하는데 이때 사용되는 것이 위의 types block이다.
실제 파일을 log해보면 대부분의 mime type은 모두 선언되어 있지만 만약 client가 mime.types에 선언되지 않은 type의 file을 요구할 때 사용할 default type이 필요하다면 default_type directive를 사용할 수 있다.
... location /user/ { default_type application/...; }
제한 관련 설정
limit_except : 특정 location으로 들어오는 request 중 설정한 http method외에 다른 method request을 막을 때 사용할 수 있다. 사용 가능한 범위는 location이다.
아래 코드는 member location은 allow에 선언된 client가 보내는 GET과 HEAD method만 허용하는 예제이다. GET method를 설정하면 HEAD method 역시 허용된다.
... location /member/ { limit_except GET { allow 192.168.1.0/32; deny all; } }limit_rate : response 전송 rate을 제한한다. limit_rate에 설정하는 값은 rate은 초당 bytes로 설정한다. 만약 다음과 같이 설정하면 response 전송 rate는 초당 700 kilobytes로 제한된다. 사용가능한 범위는 http, server, location block이다.
limit_rate 700k;satisfy : client가 특정 resoruce에 접속하기 위해 충족 해야 하는 조건 중 모든 조건을 충족해야 하는지 혹은 하나만 충족하면 되는지 여부를 결정한다. 사용 가능한 범위는 location block이다.
location /member/ { satisfy any; allow 192.168.1.0/32; deny all; auth_basic "Authentication process"; auth_basic_user_file conf/htpasswd; }위의 예제에서 satisfy directive가 any가 설정되어 있기에 client가 allow 또는 auth_basic 둘 중에 하나만 만족해도 member location에 대한 request를 허용한다. 만약 satisfy를 all로 설정하면 두 개의 조건을 모두 만족하는 client에게만 member location에 대한 request를 허용한다.
internal : 특정 location block을 internal request를 통해서만 접근하게 만든다. 즉, 외부에서는 특정 location을 접근하지 못하게 막으며 만약 외부에서 접근시 404 status code를 반환한다.
location /member/ { internal; }위의 예제 코드는 member location은 internal request만 허용한다. Nginx documentation에 따르면 internal request로 취급되는 사항은 다음과 같다.
requests redirected by the error_page, index, internal_redirect, random_index, and try_files directives
requests redirected by the “X-Accel-Redirect” response header field from an upstream server
subrequests formed by the “
include virtual” command of the ngx_http_ssi_module module, by the ngx_http_addition_module module directives, and by auth_request and mirror directivesrequests changed by the rewrite directive.
잘못된 설정으로 인해 internal redirection이 끊임없이 발생하는 상황을 방지하고자 nginx는 request당 internal redirection을 최대 10회로 제한한다. 제한 횟수가 넘어가면 nginx는 500 status code를 반환한다.
![[ 살펴보기 ] RDB - Relationships](https://cdn.hashnode.com/res/hashnode/image/upload/v1739711556668/48dc9e84-a621-42aa-9c9f-5fc5c436f0ec.jpeg)
![[ 살펴보기 ] MySQL - Data types](https://cdn.hashnode.com/res/hashnode/image/upload/v1739593589113/530f8704-4d27-42c9-a451-bb5c63150b99.jpeg)
![[ 살펴보기 ] TypeORM - Transactions, Migration](https://cdn.hashnode.com/res/hashnode/image/upload/v1739106042581/980b8133-61d4-406a-a026-65be9c28eace.jpeg)
![[ 살펴보기 ] TypeORM - Relations](https://cdn.hashnode.com/res/hashnode/image/upload/v1738666874402/b688bd0b-b6bb-4f43-87d8-c1b46b59f1b7.jpeg)
![[ 살펴보기 ] TypeORM - Basics](https://cdn.hashnode.com/res/hashnode/image/upload/v1738666803591/bef5df17-7dc7-4123-ae55-004d5042df39.jpeg)