본문 바로가기
개발&프로그래밍

[HTTP] HTTP 주요 헤더와 활용법

by 재아군 2025. 2. 21.

HTTP 주요 헤더와 활용법

1. 일반 헤더 (General Headers)

Connection

  • 현재의 전송이 완료된 후 네트워크 접속을 유지할지 결정
    Connection: keep-alive
    Connection: close

Date

  • 메시지가 생성된 날짜와 시간
    Date: Wed, 19 Feb 2025 08:30:00 GMT

 

2. 요청 헤더 (Request Headers)

Accept

  • 클라이언트가 처리 가능한 컨텐츠 타입
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

Authorization

  • 인증 토큰이나 인증 정보를 서버로 전송
    Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
    Authorization: Basic dXNlcjpwYXNzd29yZA==

User-Agent

  • 클라이언트 애플리케이션 정보
    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36

Cookie

  • 서버에 의해 이전에 저장된 쿠키를 전달
    Cookie: sessionId=abc123; userId=789

 

3. 응답 헤더 (Response Headers)

Content-Type

  • 리소스의 미디어 타입
    Content-Type: text/html; charset=UTF-8
    Content-Type: application/json
    Content-Type: multipart/form-data; boundary=boundary123

Content-Length

  • 응답 본문의 크기 (바이트 단위)
    Content-Length: 2048

Set-Cookie

  • 클라이언트에 쿠키를 저장하도록 지시
    Set-Cookie: sessionId=abc123; HttpOnly; Secure; SameSite=Strict
    Set-Cookie: userId=789; Max-Age=3600; Path=/

Cache-Control

  • 캐싱 정책을 정의
    Cache-Control: no-cache
    Cache-Control: public, max-age=31536000
    Cache-Control: private, must-revalidate

 

4. 보안 관련 헤더

Content-Security-Policy (CSP)

  • XSS 공격 등을 방지하기 위한 보안 정책
    Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline';

Strict-Transport-Security (HSTS)

  • HTTPS 사용을 강제
    Strict-Transport-Security: max-age=31536000; includeSubDomains

X-Frame-Options

  • 클릭재킹 공격 방지
    X-Frame-Options: DENY
    X-Frame-Options: SAMEORIGIN

 

5. 성능 관련 헤더

ETag

  • 리소스의 특정 버전에 대한 식별자
    ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"

Last-Modified

  • 리소스의 마지막 수정 시간
    Last-Modified: Wed, 19 Feb 2025 08:30:00 GMT

 

6. CORS 관련 헤더

Access-Control-Allow-Origin

  • 크로스 오리진 리소스 공유 허용 
  • Access-Control-Allow-Origin: *
    Access-Control-Allow-Origin: https://example.com

Access-Control-Allow-Methods

  • 허용되는 HTTP 메소드 지정
    Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS

 

7. 실제 사용 예제

REST API 요청/응답

// 요청
fetch('https://api.example.com/users', {
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + token,
        'Accept': 'application/json'
    }
});

// Express에서의 응답
app.get('/api/users', (req, res) => {
    res.set({
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache',
        'X-Custom-Header': 'custom value'
    }).send(users);
});

 

파일 업로드

const formData = new FormData();
formData.append('file', file);

fetch('/upload', {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
    },
    body: formData
});

 

보안 설정 (Express)

app.use((req, res, next) => {
    res.set({
        'Content-Security-Policy': "default-src 'self'",
        'Strict-Transport-Security': 'max-age=31536000',
        'X-Frame-Options': 'DENY',
        'X-Content-Type-Options': 'nosniff'
    });
    next();
});

 

8. 디버깅 팁

크롬 개발자 도구에서 헤더 확인

  1. Network 탭 열기
  2. 요청 선택
  3. Headers 탭 확인

curl로 헤더 확인

curl -I https://example.com
curl -H "Authorization: Bearer token123" https://api.example.com

Node.js에서 헤더 디버깅

app.use((req, res, next) => {
    console.log('Request Headers:', req.headers);
    next();
});

 

 

댓글