Modern web mimarisinde API gateway, mikroservis yapılarının vazgeçilmez bir parçası haline geldi. Birden fazla backend servisini tek bir noktadan yönetmek, rate limiting uygulamak, authentication katmanı eklemek ve yük dengelemesi yapmak artık neredeyse her production ortamının ihtiyacı. OpenLiteSpeed bu işi üstlenmek için gayet yetenekli bir aday, üstelik NGINX veya HAProxy alternatiflerine kıyasla çok daha az kaynak tüketiyor. Bu yazıda OpenLiteSpeed’i tam anlamıyla bir API gateway olarak nasıl yapılandıracağınızı, gerçek dünya senaryolarıyla birlikte adım adım anlatacağım.
OpenLiteSpeed’i API Gateway Olarak Kullanmak
OpenLiteSpeed’i klasik bir web sunucusu olarak düşünmek onu küçümsemek olur. Event-driven mimarisi, built-in cache sistemi ve esnek rewrite engine’i ile tam teşekküllü bir reverse proxy ve API gateway görevi yapabiliyor. Özellikle küçük ve orta ölçekli mikroservis mimarilerinde, ek bir gateway katmanı kurmak yerine OpenLiteSpeed’i bu iş için kullanmak hem maliyet hem de operasyonel yük açısından ciddi avantaj sağlıyor.
Temel kullanım senaryoları şu şekilde:
- Mikroservis yönlendirmesi: Farklı path’lere gelen istekleri farklı backend servislerine iletmek
- Rate limiting: IP bazlı veya token bazlı istek sınırlama
- SSL termination: Backend servisler HTTP konuşurken dış dünyaya HTTPS sunmak
- Authentication proxy: JWT veya API key doğrulaması
- Load balancing: Aynı servisin birden fazla instance’ı arasında yük dağıtımı
- Request/Response header manipulation: Header ekleme, silme veya değiştirme
Kurulum ve Ön Hazırlık
Önce temiz bir Ubuntu 22.04 sistemde OpenLiteSpeed kurulumunu yapalım. Zaten kuruluysa bu adımı atlayabilirsiniz.
# OpenLiteSpeed repo ekleme
wget -O - https://repo.litespeed.sh | sudo bash
# Kurulum
sudo apt-get update
sudo apt-get install openlitespeed -y
# PHP (bazı gateway senaryoları için gerekli olabilir)
sudo apt-get install lsphp81 lsphp81-common lsphp81-mysql -y
# Servisi başlat
sudo systemctl start lshttpd
sudo systemctl enable lshttpd
# Admin paneli şifresini ayarla
sudo /usr/local/lsws/admin/misc/admpass.sh
Test için birkaç tane dummy backend servis ayağa kaldıralım. Gerçek ortamda bunlar Node.js, Python Flask, Go servisleri veya herhangi bir HTTP servisi olabilir.
# Basit Python HTTP sunucuları ile backend simülasyonu
# Backend 1 - Users servisi (port 8001)
mkdir -p /tmp/backend-users
cat > /tmp/backend-users/server.py << 'EOF'
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
response = {"service": "users", "path": self.path, "status": "ok"}
self.wfile.write(json.dumps(response).encode())
def log_message(self, format, *args):
pass
HTTPServer(('127.0.0.1', 8001), Handler).serve_forever()
EOF
# Backend 2 - Orders servisi (port 8002)
mkdir -p /tmp/backend-orders
cat > /tmp/backend-orders/server.py << 'EOF'
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
response = {"service": "orders", "path": self.path, "status": "ok"}
self.wfile.write(json.dumps(response).encode())
def log_message(self, format, *args):
pass
HTTPServer(('127.0.0.1', 8002), Handler).serve_forever()
EOF
# Servisleri arka planda başlat
python3 /tmp/backend-users/server.py &
python3 /tmp/backend-orders/server.py &
Virtual Host Yapılandırması
OpenLiteSpeed’in konfigürasyon dosyası /usr/local/lsws/conf/httpd_config.conf ana konfig dosyasıdır. API gateway için özel bir virtual host tanımlayacağız. Admin paneli üzerinden de yapabilirsiniz ama dosya bazlı konfig her zaman daha tekrarlanabilir.
# Virtual host dizini oluştur
sudo mkdir -p /usr/local/lsws/conf/vhosts/api-gateway
sudo mkdir -p /var/www/api-gateway/html
# Virtual host konfig dosyasını oluştur
sudo tee /usr/local/lsws/conf/vhosts/api-gateway/vhconf.conf << 'EOF'
docRoot /var/www/api-gateway/html
enableGzip 1
enableBr 1
errorlog $SERVER_ROOT/logs/api-gateway-error.log {
useServer 0
logLevel WARN
rollingSize 10M
}
accesslog $SERVER_ROOT/logs/api-gateway-access.log {
useServer 0
rollingSize 10M
keepDays 7
compressArchive 1
}
index {
useServer 0
indexFiles index.html
}
# MIME type ayarları
expires {
enableExpires 1
expiresByType application/json=A0
}
# Context tanımlamaları aşağıda yapılacak
EOF
Ana konfig dosyasına virtual host’u ekleyelim:
sudo tee -a /usr/local/lsws/conf/httpd_config.conf << 'EOF'
virtualhost api-gateway {
vhRoot /usr/local/lsws/conf/vhosts/api-gateway/
configFile $VH_ROOT/vhconf.conf
allowSymbolLink 1
enableScript 1
restrained 0
setUIDMode 0
}
listener api-listener {
address *:80
secure 0
map api-gateway *
}
EOF
Proxy Cluster ve Backend Tanımlaması
OpenLiteSpeed’de backend servislere yönlendirme yapmak için önce proxy cluster tanımlamak gerekiyor. Bu cluster’lar load balancing yapılandırmasını da içeriyor.
# Ana konfig dosyasına cluster tanımları ekle
sudo tee -a /usr/local/lsws/conf/httpd_config.conf << 'EOF'
# Users servis cluster
cluster users-cluster {
type PROXY
maxConns 100
pcKeepAliveTimeout 30
inFlight 1
retryOn err_resp
retryCount 2
checkInterval 5
maxRetries 2
respBuffer 0
worker localhost:8001 {
addr 127.0.0.1:8001
maxConns 50
pcKeepAliveTimeout 30
priority 1
pingPath /health
}
}
# Orders servis cluster
cluster orders-cluster {
type PROXY
maxConns 100
pcKeepAliveTimeout 30
inFlight 1
retryOn err_resp
retryCount 2
worker localhost:8002 {
addr 127.0.0.1:8002
maxConns 50
pcKeepAliveTimeout 30
priority 1
pingPath /health
}
}
EOF
Path Bazlı Yönlendirme
Şimdi gelen istekleri path’e göre doğru backend’e yönlendirelim. Bu API gateway’in kalbi. /api/users/ istekleri users servisine, /api/orders/ istekleri orders servisine gitsin.
# Virtual host konfig dosyasını düzenle
sudo tee -a /usr/local/lsws/conf/vhosts/api-gateway/vhconf.conf << 'EOF'
# Users API context
context /api/users/ {
type PROXY
handler users-cluster
addDefaultCharset off
rewrite {
enable 1
rules <<<END_RULES
RewriteRule ^/api/users/(.*)$ /$1 [P,L]
END_RULES
}
}
# Orders API context
context /api/orders/ {
type PROXY
handler orders-cluster
addDefaultCharset off
rewrite {
enable 1
rules <<<END_RULES
RewriteRule ^/api/orders/(.*)$ /$1 [P,L]
END_RULES
}
}
# Health check endpoint
context /health {
type NULL
location /var/www/api-gateway/html/health.json
}
EOF
# Health check dosyası oluştur
echo '{"status": "healthy", "gateway": "openlitespeed"}' | sudo tee /var/www/api-gateway/html/health.json
Rate Limiting Yapılandırması
API gateway’in en kritik özelliklerinden biri rate limiting. OpenLiteSpeed’in built-in throttle modülünü kullanarak bunu yapılandırabiliriz. Ayrıca daha gelişmiş senaryolar için mod_security ile entegrasyon da mümkün.
# Ana konfig dosyasına throttle ayarları ekle
sudo tee -a /usr/local/lsws/conf/httpd_config.conf << 'EOF'
# Throttle konfigürasyonu
throttle_control {
# IP bazlı statik throttle
# Saniyede max 100 istek, burst 200
staticReqPerSec 100
dynReqPerSec 50
outBandwidth 0
inBandwidth 0
softLimit 85
hardLimit 100
gracePeriod 15
banPeriod 300
}
EOF
Virtual host seviyesinde daha granüler rate limiting için rewrite kuralları kullanabiliriz:
# Virtual host'a rate limit rewrite kuralları ekle
sudo tee -a /usr/local/lsws/conf/vhosts/api-gateway/vhconf.conf << 'EOF'
rewrite {
enable 1
rules <<<END_RULES
# Rate limit header kontrolü - API key yoksa kısıtla
RewriteCond %{HTTP:X-API-Key} ^$
RewriteCond %{REQUEST_URI} ^/api/
RewriteRule ^(.*)$ /error/401.json [L,R=401]
# Bot trafiğini engelle
RewriteCond %{HTTP_USER_AGENT} (bot|crawler|spider|scraper) [NC]
RewriteRule ^(.*)$ - [F,L]
END_RULES
}
EOF
SSL Termination
Production ortamında API gateway’inizin HTTPS üzerinden çalışması şart. OpenLiteSpeed’de SSL termination yapılandırması:
# SSL sertifikası al (certbot ile)
sudo apt-get install certbot -y
sudo certbot certonly --standalone -d api.yourdomain.com --non-interactive --agree-tos -m [email protected]
# Ana konfig'e HTTPS listener ekle
sudo tee -a /usr/local/lsws/conf/httpd_config.conf << 'EOF'
listener api-ssl-listener {
address *:443
secure 1
keyFile /etc/letsencrypt/live/api.yourdomain.com/privkey.pem
certFile /etc/letsencrypt/live/api.yourdomain.com/fullchain.pem
certChain 1
sslProtocol 24
ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384
enableECDHE 1
renegProtection 1
sslSessionCache 1
enableSpdy 15
enableQuic 1
map api-gateway *
}
EOF
# HTTP'den HTTPS'e yönlendirme
sudo tee -a /usr/local/lsws/conf/vhosts/api-gateway/vhconf.conf << 'EOF'
# HTTP -> HTTPS redirect
rewrite {
enable 1
rules <<<END_RULES
RewriteCond %{HTTPS} !on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
END_RULES
}
EOF
Header Manipulation ve CORS
API gateway’in önemli görevlerinden biri header yönetimi. Backend servislerden gelen response header’larını manipüle etmek, güvenlik header’ları eklemek ve CORS politikalarını merkezi olarak yönetmek:
sudo tee -a /usr/local/lsws/conf/vhosts/api-gateway/vhconf.conf << 'EOF'
# Güvenlik ve CORS header'ları
module mod_security {
# Header manipülasyonu için custom kurallar
}
# Context seviyesinde header ayarları
context /api/ {
type PROXY
# CORS header'ları
extraHeaders <<<END_HEADERS
Access-Control-Allow-Origin: https://app.yourdomain.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization, X-API-Key
Access-Control-Max-Age: 86400
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Strict-Transport-Security: max-age=31536000; includeSubDomains
END_HEADERS
# Backend'e iletilmeyecek header'ları temizle
addReqHeaders <<<END_REQ_HEADERS
X-Forwarded-For: %{REMOTE_ADDR}e
X-Real-IP: %{REMOTE_ADDR}e
X-Gateway: OpenLiteSpeed
END_REQ_HEADERS
}
EOF
Load Balancing ile Yüksek Erişilebilirlik
Gerçek production senaryosunda her mikro servisin birden fazla instance’ı çalışıyor. Aşağıda weighted round-robin load balancing örneği:
# Çoklu backend ile gelişmiş cluster yapılandırması
sudo tee -a /usr/local/lsws/conf/httpd_config.conf << 'EOF'
# Users servis - production cluster (3 instance)
cluster users-prod-cluster {
type PROXY
maxConns 500
pcKeepAliveTimeout 60
inFlight 1
retryOn err_resp timeout
retryCount 3
checkInterval 10
maxRetries 3
respBuffer 0
# Primary instance - daha güçlü sunucu, daha yüksek ağırlık
worker users-primary {
addr 192.168.1.10:8001
maxConns 200
pcKeepAliveTimeout 60
priority 1
pingPath /health
pingInterval 5
pingTimeout 2
}
# Secondary instance
worker users-secondary {
addr 192.168.1.11:8001
maxConns 150
pcKeepAliveTimeout 60
priority 2
pingPath /health
pingInterval 5
pingTimeout 2
}
# Tertiary instance - sadece failover için
worker users-tertiary {
addr 192.168.1.12:8001
maxConns 100
pcKeepAliveTimeout 60
priority 3
pingPath /health
pingInterval 5
pingTimeout 2
}
}
EOF
Monitoring ve Logging
API gateway olarak kullanılan bir sistemi izlemek çok önemli. OpenLiteSpeed’in log formatını API trafiğini analiz etmeye uygun şekilde ayarlayalım:
# Özel access log formatı tanımla
sudo tee -a /usr/local/lsws/conf/vhosts/api-gateway/vhconf.conf << 'EOF'
# JSON formatında structured logging
accesslog /var/log/openlitespeed/api-access.log {
useServer 0
rollingSize 100M
keepDays 30
compressArchive 1
logFormat '{"timestamp":"%{%Y-%m-%dT%H:%M:%S}t","remote_addr":"%h","method":"%m","uri":"%U","protocol":"%H","status":%s,"bytes_sent":%b,"referer":"%{Referer}i","user_agent":"%{User-Agent}i","api_key":"%{X-API-Key}i","x_forwarded_for":"%{X-Forwarded-For}i","response_time":%{ms}T}'
}
EOF
# Log analizi için basit script
sudo tee /usr/local/bin/api-gateway-stats.sh << 'SCRIPT'
#!/bin/bash
LOG_FILE="/var/log/openlitespeed/api-access.log"
echo "=== API Gateway Istatistikleri ==="
echo ""
echo "Son 1 saatteki toplam istek:"
grep "$(date -d '1 hour ago' '+%Y-%m-%dT%H')" $LOG_FILE | wc -l
echo ""
echo "HTTP status kodu dagilimi:"
grep "$(date '+%Y-%m-%dT%H')" $LOG_FILE | python3 -c "
import sys, json
from collections import Counter
statuses = []
for line in sys.stdin:
try:
data = json.loads(line)
statuses.append(str(data['status']))
except:
pass
for status, count in sorted(Counter(statuses).items()):
print(f' HTTP {status}: {count} istek')
"
echo ""
echo "En cok istek atan IP'ler (Top 10):"
grep "$(date '+%Y-%m-%dT%H')" $LOG_FILE | python3 -c "
import sys, json
from collections import Counter
ips = []
for line in sys.stdin:
try:
data = json.loads(line)
ips.append(data['remote_addr'])
except:
pass
for ip, count in Counter(ips).most_common(10):
print(f' {ip}: {count} istek')
"
SCRIPT
sudo chmod +x /usr/local/bin/api-gateway-stats.sh
Gerçek Dünya Senaryosu: E-ticaret API Gateway
Haydi tüm bu parçaları bir araya getirelim. Bir e-ticaret platformunun API gateway yapılandırması şu şekilde görünür:
# Tüm servisleri tek bir konfig'de birleştirme
sudo tee /usr/local/lsws/conf/vhosts/api-gateway/vhconf.conf << 'EOF'
docRoot /var/www/api-gateway/html
enableGzip 1
enableBr 1
# Structured logging
accesslog /var/log/openlitespeed/api-access.log {
useServer 0
rollingSize 100M
keepDays 30
compressArchive 1
}
errorlog /var/log/openlitespeed/api-error.log {
useServer 0
logLevel WARN
rollingSize 10M
}
# Global rewrite kuralları
rewrite {
enable 1
rules <<<END_RULES
# HTTP -> HTTPS zorla
RewriteCond %{HTTPS} !on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# Versiyonlama: /v1/ prefix'ini kaldır ve header'a ekle
RewriteRule ^/v1/(.*)$ /$1 [E=API_VERSION:v1,PT]
RewriteRule ^/v2/(.*)$ /$1 [E=API_VERSION:v2,PT]
# OPTIONS preflight için hızlı yanıt
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ - [R=200,L]
END_RULES
}
# Users/Auth servisi
context /users {
type PROXY
handler users-cluster
addDefaultCharset off
extraHeaders <<<END
X-Service: users
Cache-Control: no-store
END
}
# Products servisi - caching aktif
context /products {
type PROXY
handler products-cluster
addDefaultCharset off
extraHeaders <<<END
X-Service: products
Cache-Control: public, max-age=60
END
}
# Orders servisi
context /orders {
type PROXY
handler orders-cluster
addDefaultCharset off
extraHeaders <<<END
X-Service: orders
Cache-Control: no-store
END
}
# Payment servisi - extra güvenlik
context /payments {
type PROXY
handler payments-cluster
addDefaultCharset off
rewrite {
enable 1
rules <<<END_RULES
# Sadece POST ve GET izin ver
RewriteCond %{REQUEST_METHOD} !^(POST|GET)$
RewriteRule ^(.*)$ - [F,L]
END_RULES
}
}
# Gateway health check
context /gateway/health {
type NULL
location /var/www/api-gateway/html/health.json
}
EOF
# Servisi yeniden başlat
sudo systemctl restart lshttpd
# Konfigürasyonu test et
curl -s http://localhost/gateway/health
curl -s -H "X-API-Key: test-key" http://localhost/api/users/profile
curl -s -H "X-API-Key: test-key" http://localhost/api/orders/list
Yapılandırmayı Test Etme
Kurulumun doğru çalıştığını doğrulamak için kapsamlı testler yapalım:
#!/bin/bash
# API Gateway test script
GATEWAY_URL="http://localhost"
API_KEY="your-api-key-here"
PASS=0
FAIL=0
test_endpoint() {
local name=$1
local url=$2
local expected_status=$3
local headers=${4:-""}
if [ -n "$headers" ]; then
status=$(curl -s -o /dev/null -w "%{http_code}" -H "$headers" "$url")
else
status=$(curl -s -o /dev/null -w "%{http_code}" "$url")
fi
if [ "$status" = "$expected_status" ]; then
echo "PASS: $name (HTTP $status)"
((PASS++))
else
echo "FAIL: $name (Beklenen: $expected_status, Alınan: $status)"
((FAIL++))
fi
}
echo "=== API Gateway Testleri ==="
echo ""
# Health check
test_endpoint "Gateway health check" "$GATEWAY_URL/gateway/health" "200"
# API key olmadan istek (401 beklenir)
test_endpoint "API key olmadan istek" "$GATEWAY_URL/api/users/profile" "401"
# Geçerli API key ile istek
test_endpoint "Users servisi" "$GATEWAY_URL/api/users/profile" "200" "X-API-Key: $API_KEY"
test_endpoint "Orders servisi" "$GATEWAY_URL/api/orders/list" "200" "X-API-Key: $API_KEY"
# CORS preflight
test_endpoint "CORS preflight" "$GATEWAY_URL/api/users/" "200" "Access-Control-Request-Method: GET"
echo ""
echo "=== Sonuclar ==="
echo "Gecen: $PASS | Kalan: $FAIL"
Sonuç
OpenLiteSpeed’i API gateway olarak yapılandırmak ilk bakışta karmaşık görünebilir, ancak bir kez oturdurduğunuzda hem yönetimi hem de performansı açısından oldukça tatmin edici bir çözüm elde ediyorsunuz. NGINX’e kıyasla bellek tüketimi daha düşük, event-driven mimarisi sayesinde yüksek eşzamanlı bağlantı sayısını rahatlıkla kaldırıyor.
Bu yazıda anlattığım yaklaşımın artıları:
- Tek nokta yönetim: Tüm API trafiği tek yerden geçiyor, loglama ve monitoring merkezi
- SSL termination: Backend servisleriniz HTTPS karmaşasıyla uğraşmak zorunda değil
- Esneklik: Path bazlı yönlendirme, header manipülasyonu ve rewrite kuralları ile neredeyse her senaryoyu karşılayabilirsiniz
- Maliyet etkinliği: Ayrı bir API gateway çözümü için ek sunucu veya lisans maliyeti yok
Eksik kalan bazı noktalar da var. Örneğin, JWT doğrulaması için harici bir modül veya küçük bir middleware servisi gerekiyor. Çok karmaşık transformation senaryolarında Kong veya Traefik gibi dedicated gateway çözümleri daha iyi seçenek olabilir. Ancak büyük çoğunluğun ihtiyaçları için OpenLiteSpeed fazlasıyla yeterli. Production’a almadan önce yük testlerini yapmayı ve monitoring altyapısını kurmayı unutmayın. Bir sonraki yazıda OpenLiteSpeed ile ModSecurity entegrasyonunu ve API trafiği için WAF kurallarını anlatacağım.