본문 바로가기
Nginx

[NGINX] Nginx의 기본 변수 받아오기와 활용법

by 임혁진 2025. 4. 19.

Nginx를 웹 서버나 리버스 프록시로 사용할 때, 요청/응답의 다양한 정보를 변수로 참조할 수 있습니다. 이 변수들을 적절히 활용하면, 클라이언트의 IP 확인, 로그 포맷 커스터마이징, 헤더 설정, 조건 분기 처리 등 여러 작업을 유연하게 처리할 수 있습니다.

 

Nginx에서 사용 가능한 변수란?

Nginx는 요청이 들어올 때 다양한 정보를 변수로 제공합니다.
대표적으로는 클라이언트 정보, 서버 정보, 요청 URL, 요청 헤더 등이 있습니다.

location / {
    add_header X-Client-IP $remote_addr;
    return 200 "Hello from $host\n";
}

주요 Nginx 변수 목록

 

변수 설명
$remote_port 클라이언트의 포트
$host 요청의 호스트 헤더 값
$http_user_agent 클라이언트의 User-Agent
$request_uri 전체 요청 URI (쿼리 스트링 포함)
$uri 쿼리스트링 제외한 경로
$request_method GET, POST 등 HTTP 메소드
$server_protocol HTTP/1.1, HTTP/2 등
$scheme http 또는 https
$http_cookie 요청 쿠키 전체
$http_<HEADER> 특정 요청 헤더의 값
$query_string 쿼리 스트링
$remote_addr 클라이언트의 IP 주소

예제: 클라이언트 IP 확인

server {
    listen 80;
    server_name localhost;

    location /ip {
        default_type text/plain;
        return 200 "IP : $remote_addr\n";
    }
}

접속 시 결과:

IP: EC2 IP ex) 52.11.233.111

예제: 사용자 에이전트 로그 출력

log_format custom_log '$remote_addr - [$time_local] '
                      '"$request" "$http_agent"';

access_log /var/log/nginx/access.log custom_log;

로그에 사용자 브라우저 정보를 포함시킬 수 있어 분석이나 디버깅에 유용합니다.


특정 헤더 값 받기 ($http_ 변수)

location /debug {
    return 200 "Token: $http_authorization\n";
}
클라이언트가 Authorization 헤더를 보내면 이를 직접 확인할 수 있어요.
예: Authorization: Bearer xxx.yyy.zzz

 

 


조건문에서 변수 활용하기

location /admin {
    if ($remote_addr != "192.168.0.1") {
        return 403;
    }

    proxy_pass http://localhost:8080;
}

특정 IP 외에는 관리자 페이지 접근 금지 같은 조건 처리 가능.

 


변수와 정규표현식 조합

location ~ ^/product/(\d+)$ {
    set $product_id $1;
    proxy_pass http://backend/product?id=$product_id;
}

정규식으로 경로에서 ID를 추출해 백엔드로 전달할 수도 있습니다.

 


마무리 전체 nginx.conf 예시

user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  custom_log  '$remote_addr - $remote_user [$time_local] '
                             '"$request" $status $body_bytes_sent '
                             '"$http_referer" "$http_agent"';

    access_log  /var/log/nginx/access.log  custom_log;

    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;

        # 클라이언트 IP 확인
        location /ip {
            default_type text/plain;
            return 200 "IP: $remote_addr\n";
        }

        # 요청 헤더 Authorization 확인
        location /debug {
            default_type text/plain;
            return 200 "Authorization Header: $http_authorization\n";
        }

        # 관리자 페이지 접근 제한 (지정된 IP만 허용)
        location /admin {
            if ($remote_addr != "192.168.0.100") {
                return 403;
            }

            proxy_pass http://localhost:8080;
        }

        # 기본 라우팅
        location / {
            proxy_pass http://localhost:8080;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
}

nginx.conf 설명

설정 의미
/ip 클라이언트 IP 반환
/debug 특정 요청 헤더 출력
/admin 특정 IP만 접근 가능
proxy_set_header 프록시 시 원본 정보 전달 (중요)
log_format custom_log 사용자 정의 로그 포맷, user-agent 포함

관련 공식 문서