리눅스
Nginx에 커스텀 헤더 추가하기
변군이글루
2025. 10. 20. 22:36
반응형
Nginx에 커스텀 헤더 추가하기(add_header 지시어)
기본 개념
add_header는 nginx가 클라이언트에 응답을 보낼 때 원하는 HTTP 헤더를 추가하는 설정입니다.
형식
add_header <헤더이름> <값> [always];
- 헤더이름 : X-Served-By
- 값 : 문자열 혹은 nginx 변수 ($hostname, $remote_addr, $server_addr, $NODE_NAME 등)
- always : 4xx, 5xx 응답에도 항상 헤더를 포함할 때 사용
커스텀 헤더 설정
고정 문자열 방식
- 서버 이름을 직접 지정하는 가장 단순한 방식입니다.
sudo vim /etc/nginx/nginx.conf
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
server_tokens off;
add_header X-Served-By web-01 always;
# SSL 설정
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CHACHA20-POLY1305;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
...
include /etc/nginx/conf.d/*.conf;
}
nginx 설정 테스트
sudo nginx -t
설정 재적용(무중단 reload)
sudo nginx -s reload
헤더 확인(결과)
curl -I https://customheaders.scbyun.com
HTTP/2 200
Server: nginx
Date: Mon, 20 Oct 2025 12:00:00 GMT
Content-Type: text/html
Content-Length: 1234
Last-Modified: Mon, 20 Oct 2025 10:00:00 GMT
Connection: keep-alive
x-served-by: web-01
-I 옵션은 헤더만 출력
-v 옵션을 쓰면 더 상세한 요청/응답 과정을 확인할 수 있습니다.
728x90
시스템 호스트명 자동 표시
- $hostname 변수는 서버의 호스트명을 자동으로 가져옵니다.
vim /etc/nginx/nginx.conf
http {
add_header X-Served-By $hostname always;
}
sudo nginx -t
sudo nginx -s reload
헤더 확인(결과)
curl -s -D - -o /dev/null https://customheaders.scbyun.com/ | grep -i X-Served-By
x-served-by: webServer-01
여러 서버(webServer-01, webServer-02, webServer-03…)가 있을 때 어떤 서버가 응답했는지 바로 식별 가능.
설정 위치와 상속 관계
블록 | 적용 범위 | 설명 |
http | 전체 서버 공통 | 모든 server/location에 적용 |
server | 특정 가상호스트만 | 해당 도메인 요청에만 적용 |
location | 특정 경로만 | /health 등 특정 엔드포인트에만 적용 |
주의
하위 블록(server 또는 location)에서 add_header를 다시 선언하면 상위 블록의 설정은 무시됩니다.
따라서 모든 응답에 헤더를 유지하고 싶다면 always 옵션을 함께 써줘야 합니다.
추천 설정
http {
add_header X-Served-By $hostname always;
server {
listen 80;
server_name example.com;
location / {
root /usr/share/nginx/html;
}
location = /health {
add_header Content-Type text/plain always;
return 200 'OK';
}
}
}
출력 결과
curl -I http://example.com
HTTP/1.1 200 OK
X-Served-By: web1
참고URL
- nginx documentation : Module ngx_http_headers_module
728x90
반응형