🌍 Networking

Proxy

Proxy

An intermediary between client and server. Caching, security, load balancing.

Forward vs Reverse Proxy

Proxies are broadly divided into two types according to their location and role. A Forward Proxy acts on behalf of the client for external internet access, while a Reverse Proxy protects internal servers and distributes traffic on the server side.

→
Forward Proxy
Client-Side Proxy

It forwards requests on behalf of the client when the client accesses external servers. It hides the client's IP and performs access control and content filtering.

Corporate network internet access control
Guaranteeing user anonymity (IP hiding)
Bypassing region-restricted content
Blocking access to malicious sites
Representative Tools
Squid Privoxy CCProxy
←
Reverse Proxy
Server-Side Proxy

It receives external requests and forwards them to internal servers. It hides the server's actual IP and handles load balancing, SSL termination, caching, and more.

Load balancing (traffic distribution)
SSL/TLS termination (certificate management)
Static content caching
DDoS attack defense
Representative Tools
Nginx HAProxy Traefik
💻
Client
⟶
🛡
Forward Proxy
⟶
🌐
Internet
Client IP hiding | Access control | Content filtering
🌐
Internet
⟶
🛡
Reverse Proxy
⟶
🖥
Backend Servers
SSL termination | Load balancing | Caching | Security
💻
User
⟶
⚡
CDN Edge
⟶
🛡
Nginx
⟶
🖥
Origin
Cloudflare/Akamai (Edge) + Nginx (Origin) dual caching architecture

📦 Proxy Caching Mechanism

Proxy caching stores frequently requested content on the proxy server to reduce the load on the origin server and improve response speed. An appropriate caching strategy can reduce server costs by 70-90%.

📋 Cache-Control Header

It finely controls caching behavior with directives such as max-age, no-cache, no-store, private, and public.

🔧 ETag/Last-Modified

It checks only whether the content has changed through conditional requests (If-None-Match, If-Modified-Since) and saves bandwidth with a 304 response.

🔢 Cache Key

It distinguishes caches by combining the URL, query parameters, and headers (Accept-Language, Accept-Encoding).

🔄 Cache Invalidation

It removes stale cache through PURGE requests, TTL expiration, and tag-based invalidation. It is "one of the hardest problems in computer science."

<10ms
Cache Hit Response Time
80-95%
Typical Hit Rate
70-90%
Server Load Reduction

🔒 Proxy Security Features

A proxy is a core component of network security. Positioned between the client and the server, it filters malicious traffic, protects sensitive information, and detects/blocks attacks.

🔒
SSL/TLS Termination
Decrypts HTTPS at the proxy to reduce the burden on backend servers. Centralizes certificate management.
🛡
WAF (Web Application Firewall)
Detects and blocks OWASP Top 10 attacks such as SQL Injection, XSS, and CSRF.
🌟
Rate Limiting
Limits the number of requests per IP/user to prevent brute-force attacks and API abuse.
🚫
DDoS Defense
Absorbs large-scale traffic and guarantees service availability through bot detection and CAPTCHA challenges.
👁
IP Masking
Hides the actual server IP to prevent direct attacks. Acts as an Origin Shield.
📝
Logging & Monitoring
Collects all traffic logs, detects anomalies, and supports security audits.

🛠 Tool Comparison: Nginx vs Squid vs HAProxy

The choice of proxy tool depends on its purpose. Nginx is representative for web servers/reverse proxies, Squid for Forward Proxy/caching, and HAProxy for high-performance load balancing.

Tool Main use Reverse Proxy Forward Proxy Caching Features
Nginx Popular Web server, reverse proxy ✔ Excellent ✘ Limited ✔ Very good Lightweight, high concurrency, simple configuration
Squid Forward Proxy, caching ✔ Supported ✔ Excellent ✔ Excellent Powerful ACL, large-capacity cache
HAProxy Enterprise Load balancing, TCP proxy ✔ Excellent ✘ Not supported ✘ Not supported Ultra-high performance, L4/L7 support, health checks
Traefik Cloud-native proxy ✔ Excellent ✘ Not supported ✘ Limited Automatic configuration, Docker/K8s integration
Envoy Service mesh, API Gateway ✔ Excellent ✘ Not supported ✔ Supported gRPC support, Observability

📈 Proxy Traffic Simulation

See in real time how a proxy processes requests. You can visually understand the flow of cache hits, cache misses, and blocked requests.

[00:00:00] → GET /api/users CACHE MISS - Origin server request (245ms)
[00:00:01] → GET /api/users CACHE HIT - Cache response (3ms)
[00:00:02] → GET /static/logo.png CACHE HIT - Cache response (1ms)
[00:00:03] → POST /api/login - Passed through proxy (89ms)
[00:00:04] → GET /admin/config BLOCKED - Access denied (IP blocked)

📖 Detailed Explanation

A proxy means 'agent' or 'representative.' It is a server that sits between the client and the server in a network and relays requests and responses. Instead of the client connecting directly to the server, the proxy server forwards the request on its behalf, receives the response, and passes it back to the client. This provides various benefits such as caching, security, anonymity, and load balancing.

Proxies are broadly divided into Forward Proxy and Reverse Proxy. A Forward Proxy sits on the client side and forwards the client's requests on its behalf, and is used for internet access control in corporate networks and for hiding users' IP addresses. Squid and Privoxy are representative examples. A Reverse Proxy sits on the server side and distributes external requests to internal servers, with Nginx and HAProxy being representative.

The caching function of a proxy greatly reduces network traffic. If frequently requested content is stored on the proxy server, it can respond quickly without sending the request to the origin server. A CDN (Content Delivery Network) can also be viewed as a kind of distributed caching proxy, which caches content on edge servers deployed around the world and serves users from the location closest to them.

From a security perspective, a proxy performs various roles such as firewall, SSL/TLS termination, DDoS defense, and malicious traffic filtering. In modern web architecture, reverse proxies such as Nginx or Envoy act as an API Gateway and handle cross-cutting concerns such as authentication, rate limiting, logging, and monitoring. In a Kubernetes environment, the Ingress Controller takes on this role.

💻 Code Example

# Nginx Reverse Proxy 설정 (/etc/nginx/nginx.conf)

# 기본 리버스 프록시 설정
server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://backend-server: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;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

# 로드 밸런싱 설정
upstream backend {
    least_conn;  # 최소 연결 알고리즘
    server backend1:8080 weight=3;
    server backend2:8080 weight=2;
    server backend3:8080 backup;  # 백업 서버
}

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

    ssl_certificate /etc/ssl/certs/example.crt;
    ssl_certificate_key /etc/ssl/private/example.key;

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

    location /api/ {
        proxy_pass http://backend;
        proxy_cache my_cache;
        proxy_cache_valid 200 10m;
        proxy_cache_valid 404 1m;

        # 타임아웃 설정
        proxy_connect_timeout 60s;
        proxy_read_timeout 60s;
    }
}
import requests
from http.server import HTTPServer, BaseHTTPRequestHandler
import urllib.request

# 프록시를 통한 HTTP 요청 (requests 라이브러리)
proxies = {
    'http': 'http://proxy.example.com:8080',
    'https': 'http://proxy.example.com:8080',
}

# 프록시를 통해 요청 보내기
response = requests.get('https://api.example.com/data',
                        proxies=proxies,
                        timeout=30)
print(response.json())

# SOCKS 프록시 사용 (pip install requests[socks])
socks_proxies = {
    'http': 'socks5://localhost:9050',   # Tor
    'https': 'socks5://localhost:9050',
}
response = requests.get('https://check.torproject.org',
                        proxies=socks_proxies)


# 간단한 HTTP 프록시 서버 구현
class ProxyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        # 요청 URL로 프록시 요청
        try:
            with urllib.request.urlopen(self.path) as response:
                self.send_response(response.status)
                for header, value in response.getheaders():
                    self.send_header(header, value)
                self.end_headers()
                self.wfile.write(response.read())
        except Exception as e:
            self.send_error(500, str(e))

# 프록시 서버 실행 (포트 8888)
# server = HTTPServer(('localhost', 8888), ProxyHandler)
# server.serve_forever()

# 환경 변수로 프록시 설정
import os
os.environ['HTTP_PROXY'] = 'http://proxy.example.com:8080'
os.environ['HTTPS_PROXY'] = 'http://proxy.example.com:8080'
os.environ['NO_PROXY'] = 'localhost,127.0.0.1,.internal.com'
# Squid Forward Proxy 설정 (/etc/squid/squid.conf)

# 기본 포트 설정
http_port 3128

# 접근 제어 리스트 (ACL)
acl localnet src 10.0.0.0/8
acl localnet src 172.16.0.0/12
acl localnet src 192.168.0.0/16

acl SSL_ports port 443
acl Safe_ports port 80 443 8080

# 접근 허용/거부 규칙
http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access allow localnet
http_access deny all

# 캐싱 설정 (1GB 캐시)
cache_dir ufs /var/spool/squid 1000 16 256
maximum_object_size 100 MB
cache_mem 256 MB

# 익명성 설정 (클라이언트 IP 숨기기)
forwarded_for off
request_header_access Via deny all
request_header_access X-Forwarded-For deny all

# 차단할 도메인
acl blocked_sites dstdomain .facebook.com .youtube.com
http_access deny blocked_sites

# -------------------------------------------
# curl에서 프록시 사용
curl -x http://proxy.example.com:8080 https://api.example.com
curl --proxy socks5://localhost:9050 https://check.torproject.org

# 환경 변수로 프록시 설정 (Linux/macOS)
export http_proxy="http://proxy.example.com:8080"
export https_proxy="http://proxy.example.com:8080"
export no_proxy="localhost,127.0.0.1,.internal.com"

# Git에서 프록시 설정
git config --global http.proxy http://proxy.example.com:8080
git config --global https.proxy http://proxy.example.com:8080

# npm에서 프록시 설정
npm config set proxy http://proxy.example.com:8080
npm config set https-proxy http://proxy.example.com:8080

🗣️ Say It Like This in Practice

💬 In an architecture design meeting
"If you put Nginx in front of the API server as a reverse proxy, you can handle SSL termination, load balancing, and static file caching all at once. Since the backend servers only need to handle HTTP, performance improves, and certificate management can be done in just one place, Nginx."
💬 In a Security Review Meeting
"I think we should introduce a Forward Proxy to control outbound traffic. If internal servers must go through the proxy whenever they communicate externally, we can block access to malicious domains and monitor data leakage. We can operate it with Squid using a whitelist approach."
💬 In a Performance Optimization Discussion
"Slow API response times can be resolved with proxy caching. For GET requests that rarely change, caching them for about 10 minutes with proxy_cache in Nginx can reduce backend load by more than 80%. It would be good to also set the Cache-Control header so that CDN caching can be used as well."

⚠️ Common Mistakes & Cautions

❌
Trusting the X-Forwarded-For Header

Clients can manipulate the X-Forwarded-For header. In a proxy chain, use only the value added by the last trusted proxy. You must explicitly configure the trusted IP ranges with Nginx's realip_module.

❌
Missing WebSocket/SSE Proxy Configuration

WebSocket does not work with only a regular HTTP proxy configuration. In Nginx, you must explicitly pass the Upgrade and Connection headers, and you must also set a longer timeout so the connection is not dropped.

❌
Sensitive Data Exposure Through Caching

If a response containing user-specific personal data is cached, it may be exposed to other users. Check the Cache-Control: private, no-store header, and exclude endpoints that require authentication from caching.

✅
How to Configure a Proxy Correctly

Be sure to check the proxy header settings (X-Real-IP, X-Forwarded-For, X-Forwarded-Proto), appropriate timeout values, health check settings, and buffer size adjustments. Also configure automatic failover with proxy_next_upstream in case of failures.

🔗 Related Terms

📚 Learn More