[Nginx] Header & Expire

반응형

이번글에서는 Nginx에서 response data에 header를 추가하는 방법에 대해 알아보도록 하겠습니다.

1. Expires Header란?

nginx는 expires header를 통해 client에게 response data를 얼마나 오랫동안 client의 browser에 cache할 것인지를 알려줍니다.

image.png

예를 들어 이미지 파일과 같은 static file들은 자주 변경되지 않기 때문에 nginx는 client의 browser에게 비교적 긴 시간동안 해당 파일들을 본인들의 local browser에 cache해 놓을 것을 요청합니다.

이를 통해 향후 동일한 이미지에 대한 request를 browser의 cache로 대체함으로써 전체 service의 성능 향상을 꾀할 수가 있습니다.

image.png

반대로 data의 변경이 잦은 css와 같은 파일들은 expire date를 비교적 짧게 가져가지만 이역시도 client의 browser에 cache됩니다.

image.png

2. Set Header

이제 nginx에서 response data에 header를 설정해보도록 하겠습니다 😎.

2-1) custom header

header의 설정하기위해선 아래와 같이 location context안에 add_header 구문을 추가해주면 됩니다. 이때 add_header 구문은 header_name과 header_value 순서로 작성하면 됩니다.

server {
        listen 80;
        server_name 13.125.252.144;
        root /sites/demo;

        location =/thumb.png {
                add_header my_header "Hello Minho";
        }
}

nginx reload 후 curl -I command로 확인하면 아래와 같이 정상적으로 header가 생성된 것을 확인할 수 있습니다.

image.png

2-2) static header

사용자가 임의로 정의한 위의 my_header와는 다르게 이미 정의되어 있는 header를 사용할 수 도 있습니다. 그 중 static resource에 사용되는 hedear들은 다음과 같습니다.

Cache-Control

add_headers Cache-Control public;

이 header가 public인 response data는 client의 아무곳에나 cache될 수 있도록 허가합니다.

Pragma

add_header Pragama public;

cache-control header의 older version 입니다.

Vary

add_header Vary Accept-Encoding;

response data가 vary에 명시된 방법에 따라서 변환 될 수 있도록 허용합니다. 위의 Vary header는 reponse data를 encoding 합니다. Encoding에 대한 자세한 내용은 다음글에서 다뤄보겠습니다.

Expire

expires 60m;

client에 cache 되있는 시간을 지정합니다. 위와 같이 작성하면 response data는 60분동안 client에 cache됩니다.

3. Test

아래와 같이 nginx.conf를 변경 후 테스트 해보겠습니다 😎.

image.png

정상적으로 header 가 생성된 것을 확인할 수 있습니다. 👏👏👏

image.png


참고 자료 : https://www.udemy.com/course/nginx-fundamentals/


반응형

'Nginx' 카테고리의 다른 글

[Nginx] FastCGI Cache  (0) 2020.08.31
[Nginx] Compressed Response with gzip  (0) 2020.08.31
[Nginx] Adding Dynamic Module  (0) 2020.08.31
[Nginx] Buffer & Timeout  (0) 2020.08.27
[Nginx] Worker Process  (0) 2020.08.27

댓글

Designed by JB FACTORY