🌍 Networking

Reverse Proxy

Reverse Proxy

A server that relays client requests to backend servers. Implemented with Nginx, HAProxy, and others, it provides load balancing, SSL termination, caching, and security features.

📖 Detailed Explanation

A reverse proxy is an intermediary server that sits between clients and backend servers, receiving client requests on their behalf and forwarding them to the appropriate server. Clients communicate only with the reverse proxy and are unaware of the existence of the actual backend servers. This can greatly improve the security, scalability, and performance of the server infrastructure.

The core roles of a reverse proxy are load balancing, SSL/TLS termination, caching, compression, security (WAF), and API gateway functions. Representative reverse proxy software includes Nginx (No. 1 in global web server market share), HAProxy (a high-performance load balancer), Apache httpd, Traefik (cloud-native), and Envoy (service mesh).

It is easy to confuse with a Forward Proxy. A Forward Proxy acts on the client side to handle external internet access on clients' behalf (e.g., corporate firewall, VPN), while a Reverse Proxy relays client requests to internal servers on the server side. Put simply, a Forward Proxy 'hides the client,' and a Reverse Proxy 'hides the server.'

In modern Microservices architectures, a reverse proxy is essential. Netflix handles billions of requests per day with Zuul, and Cloudflare handles 25% of global traffic through reverse proxies. Kubernetes' Ingress Controller is also essentially a reverse proxy.

🔄 Forward Proxy vs Reverse Proxy

Category Forward Proxy Reverse Proxy
Location In front of the client (outbound) In front of the server (inbound)
What it hides Client IP Server IP/structure
Main uses Anonymity, access control, bypassing Load balancing, SSL, caching, security
Examples Squid, corporate proxy, VPN Nginx, HAProxy, Cloudflare
Configuration location Client/browser Server infrastructure
┌─────────────┐                              ┌─────────────┐
│  Forward    │     사용자 → 인터넷 접근     │   Reverse   │
│   Proxy     │                              │    Proxy    │
└─────────────┘                              └─────────────┘

사용자 → [Forward Proxy] → 인터넷      인터넷 → [Reverse Proxy] → 서버들
        (클라이언트 숨김)                      (서버 숨김)
                    

💻 Code Example

# /etc/nginx/nginx.conf - 리버스 프록시 기본 설정

# 업스트림 서버 그룹 (로드밸런싱)
upstream backend_servers {
    # 로드밸런싱 알고리즘: round-robin(기본), least_conn, ip_hash
    least_conn;

    server 10.0.0.1:8080 weight=3;  # 가중치 높음
    server 10.0.0.2:8080 weight=2;
    server 10.0.0.3:8080 backup;    # 백업 서버

    # 헬스체크 (유료 버전)
    keepalive 32;  # 연결 재사용
}

server {
    listen 80;
    listen 443 ssl http2;
    server_name api.example.com;

    # SSL/TLS 종료 (백엔드는 HTTP로 통신)
    ssl_certificate /etc/ssl/certs/example.crt;
    ssl_certificate_key /etc/ssl/private/example.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;

    # 캐싱 설정
    proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=api_cache:10m max_size=1g;

    location / {
        proxy_pass http://backend_servers;

        # 필수 헤더 전달
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        # 캐싱 활성화
        proxy_cache api_cache;
        proxy_cache_valid 200 10m;
        proxy_cache_valid 404 1m;

        # 타임아웃 설정
        proxy_connect_timeout 10s;
        proxy_read_timeout 30s;

        # 보안 헤더
        add_header X-Frame-Options "SAMEORIGIN" always;
        add_header X-Content-Type-Options "nosniff" always;
    }

    # WebSocket 프록시
    location /ws/ {
        proxy_pass http://backend_servers;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}
# /etc/haproxy/haproxy.cfg - 고성능 로드밸런서

global
    maxconn 50000
    log /dev/log local0
    chroot /var/lib/haproxy
    stats socket /run/haproxy/admin.sock mode 660 level admin

defaults
    mode http
    timeout connect 5s
    timeout client  30s
    timeout server  30s
    option httplog
    option dontlognull
    option forwardfor

# 프론트엔드 (리버스 프록시 진입점)
frontend http_front
    bind *:80
    bind *:443 ssl crt /etc/ssl/certs/example.pem

    # HTTP → HTTPS 리다이렉트
    http-request redirect scheme https unless { ssl_fc }

    # ACL 기반 라우팅
    acl is_api path_beg /api/
    acl is_static path_beg /static/

    use_backend api_servers if is_api
    use_backend static_servers if is_static
    default_backend web_servers

# 백엔드 서버 그룹
backend api_servers
    balance roundrobin
    option httpchk GET /health
    http-check expect status 200

    server api1 10.0.0.1:8080 check weight 100
    server api2 10.0.0.2:8080 check weight 100
    server api3 10.0.0.3:8080 check weight 50 backup

backend web_servers
    balance leastconn
    cookie SERVERID insert indirect nocache

    server web1 10.0.1.1:3000 check cookie web1
    server web2 10.0.1.2:3000 check cookie web2

backend static_servers
    balance uri
    server cdn1 10.0.2.1:80 check
    server cdn2 10.0.2.2:80 check

# 통계 대시보드
listen stats
    bind *:8404
    stats enable
    stats uri /stats
    stats auth admin:password123
// Node.js 리버스 프록시 (http-proxy-middleware)
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();

// 로깅 미들웨어
app.use((req, res, next) => {
    console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
    next();
});

// API 서버로 프록시 (로드밸런싱)
const apiServers = ['http://10.0.0.1:8080', 'http://10.0.0.2:8080'];
let currentServer = 0;

app.use('/api', createProxyMiddleware({
    router: (req) => {
        // Round-robin 로드밸런싱
        const target = apiServers[currentServer];
        currentServer = (currentServer + 1) % apiServers.length;
        return target;
    },
    changeOrigin: true,
    pathRewrite: { '^/api': '' },

    // 요청/응답 수정
    onProxyReq: (proxyReq, req, res) => {
        proxyReq.setHeader('X-Real-IP', req.ip);
        proxyReq.setHeader('X-Forwarded-For', req.ip);
    },

    onProxyRes: (proxyRes, req, res) => {
        // 보안 헤더 추가
        proxyRes.headers['X-Frame-Options'] = 'SAMEORIGIN';
        proxyRes.headers['X-Content-Type-Options'] = 'nosniff';
    },

    onError: (err, req, res) => {
        console.error('Proxy error:', err);
        res.status(502).json({ error: 'Bad Gateway' });
    }
}));

// WebSocket 프록시
app.use('/ws', createProxyMiddleware({
    target: 'ws://10.0.0.1:8080',
    ws: true,
    changeOrigin: true
}));

// 정적 파일 서버로 프록시 (캐싱)
app.use('/static', createProxyMiddleware({
    target: 'http://cdn.example.com',
    changeOrigin: true,
    selfHandleResponse: false
}));

app.listen(80, () => {
    console.log('Reverse proxy running on port 80');
});

🎯 Reverse Proxy Core Features

Feature Description Effect
Load Balancing Distributes traffic across multiple servers Scalability ↑, availability ↑
SSL Termination Handles HTTPS encryption/decryption Backend load ↓, simpler certificate management
Caching Stores responses for reuse Response time ↓, server load ↓
Compression Compresses responses with gzip/brotli Bandwidth ↓, transfer speed ↑
Security (WAF) Filters malicious requests DDoS protection, SQL Injection blocking
API Gateway Authentication, Rate Limiting, routing Unified entry point for Microservices

🗣️ Say It Like This in Practice

💬 In an Infrastructure Design Meeting
"If we put an Nginx reverse proxy in front of the API server, the proxy handles SSL termination, so the backend can communicate over HTTP. Certificate management can be done in one place, and we can also reduce backend CPU load by about 30%."
💬 In a technical interview
"A Forward Proxy handles internet access on the client side, and a Reverse Proxy distributes requests on the server side. In practice, our team used Nginx as a reverse proxy to distribute traffic across 3 Node.js servers, and automatically excluded failed servers with upstream health checks."
💬 In an Incident Response Situation
"API server #2 died from an OOM, but the reverse proxy's health check detected it and traffic was automatically distributed to #1 and #3. There was no user impact, and after the server restarted, it rejoined the Load Balancing pool."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
X-Forwarded-For header not set

When traffic passes through a reverse proxy, the backend sees the client IP as the proxy IP. Be sure to set proxy_set_header X-Real-IP and X-Forwarded-For.

❌
Load balancing without health checks

When a backend server fails, requests continue to be forwarded to the dead server. Enable HAProxy's 'option httpchk' or Nginx Plus's health_check.

❌
Connection exhaustion from unset timeouts

If the default timeout is too long, slow clients hold on to connections. Set connect_timeout to 5s and read_timeout to about 30s.

✅
Correct Reverse Proxy Configuration

Reuse backend connections with keepalive connections, enable gzip compression, and set an appropriate cache policy. Always monitor upstream response time and error rate.

🔗 Related Terms

📚 Learn More