Nginx Kapsamlı Rehber (Comprehensive Nginx Guide)
Full-stack geliştiriciler için Nginx yapılandırma, reverse proxy ve performans rehberi.
Ne zaman Nginx kullanmalıyım?
✅ Kullan: Reverse proxy, SSL termination, static file serving, load balancing, rate limiting
⚠️ Opsiyonel: Basit geliştirme ortamında -- framework'un kendi sunucusu yeterli olabilir
❌ Yapma: Nginx'i application server olarak kullanma -- her dil için kendi app server'ini kullan
Alternatifler: Apache (mod_php, .htaccess), Caddy (otomatik SSL), Traefik (container-native)
Nginx Nedir? (What is Nginx?)
Nginx (okunuşu: "engine-x") yüksek performanslı bir HTTP sunucusu, reverse proxy ve load balancer'dır. C dilinde yazılmıştır ve event-driven (olay tabanlı) mimarisi sayesinde düşük bellek tüketimi ile binlerce eş zamanlı bağlantı yönetebilir.
Nginx vs Apache Karşılaştırma (Nginx vs Apache Comparison)
| Özellik | Nginx | Apache |
|---|---|---|
| Mimari | Event-driven, async | Process/Thread-based |
| Performans (static) | Çok yüksek | İyi |
| Performans (concurrent) | Çok yüksek | Orta |
| Bellek kullanımı | Düşük | Yüksek |
| .htaccess desteği | Yok | Var |
| Modül sistemi | Derleme zamanı | Çalışma zamanı (dinamik) |
| Config syntaxı | Blok-tabanlı | XML-benzeri |
| Reverse proxy | Dahili, güçlü | mod_proxy ile |
| Yaygınlık (web) | 1 numara | 2 numara |
Genel kural: Reverse proxy ve static serving için Nginx, .htaccess gerektiren legacy projeler için Apache tercih edilir. Modern projelerde Nginx varsayılan tercihtir.
Kurulum (Installation)
Ubuntu / Debian
# Paket listesini guncelle
sudo apt update
# Nginx kur
sudo apt install nginx -y
# Servisi baslat ve otomatik baslatmayi etkinlestir
sudo systemctl start nginx
sudo systemctl enable nginx
# Durumu kontrol et
sudo systemctl status nginx
# Versiyon kontrol
nginx -vCentOS / RHEL
# EPEL deposunu ekle
sudo yum install epel-release -y
# Nginx kur
sudo yum install nginx -y
# Servisi baslat
sudo systemctl start nginx
sudo systemctl enable nginxDocker ile Kurulum (Docker Installation)
# Basit kullanim
docker run -d --name nginx -p 80:80 nginx:alpine
# Volume ile (config ve static dosyalar)
docker run -d \
--name nginx \
-p 80:80 \
-p 443:443 \
-v ./nginx.conf:/etc/nginx/nginx.conf:ro \
-v ./html:/usr/share/nginx/html:ro \
-v ./certs:/etc/nginx/certs:ro \
nginx:alpineDocker Compose örneği:
# docker-compose.yml
version: "3.8"
services:
nginx:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
- ./sites:/etc/nginx/conf.d:ro
- ./html:/usr/share/nginx/html:ro
- ./certs:/etc/nginx/certs:ro
restart: unless-stoppedTemel Komutlar (Basic Commands)
# Config test et (deployment oncesi mutlaka calistir)
sudo nginx -t
# Yapilandirmayi yeniden yukle (downtime olmadan)
sudo nginx -s reload
# Nginx'i durdur
sudo nginx -s stop
# Graceful shutdown (mevcut baglantilari tamamla)
sudo nginx -s quit
# Config dosyasinin yolunu goster
nginx -V 2>&1 | grep confTemel Yapılandırma (Basic Configuration)
Dosya Yapısı (File Structure)
/etc/nginx/
nginx.conf # Ana yapilandirma dosyasi
conf.d/ # Ek yapilandirma dosyalari (.conf)
sites-available/ # Tum site tanimlari (Ubuntu/Debian)
sites-enabled/ # Aktif siteler (symlink)
snippets/ # Tekrar kullanilabilir config parcalari
mime.types # MIME turu tanimlaringinx.conf Ana Dosyası (Main Configuration File)
# /etc/nginx/nginx.conf
user www-data;
worker_processes auto; # CPU cekirdek sayisi kadar worker
pid /run/nginx.pid;
error_log /var/log/nginx/error.log warn;
events {
worker_connections 1024; # Her worker icin max baglanti
multi_accept on; # Birden fazla baglanti kabul et
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Loglama formati
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log main;
# Performans ayarlari
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
client_max_body_size 64m;
# Gzip sikistirma
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css application/json
application/javascript text/xml application/xml
application/xml+rss text/javascript
image/svg+xml;
# Site yapilandirmalarini dahil et
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}Server Block (Sanal Sunucu / Virtual Host)
# /etc/nginx/sites-available/ornek.com
server {
listen 80;
listen [::]:80;
server_name ornek.com www.ornek.com;
root /var/www/ornek.com/public;
index index.html index.htm;
# Erisim ve hata loglari
access_log /var/log/nginx/ornek.com.access.log;
error_log /var/log/nginx/ornek.com.error.log;
location / {
try_files $uri $uri/ =404;
}
# Hata sayfalari
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
}# Siteyi etkinlestir
sudo ln -s /etc/nginx/sites-available/ornek.com /etc/nginx/sites-enabled/
sudo nginx -t && sudo nginx -s reloadLocation Blokları (Location Blocks)
server {
# Tam eslesme (exact match) -- en yuksek oncelik
location = /favicon.ico {
log_not_found off;
access_log off;
}
# Prefix eslesme (oncelikli, regex'ten once)
location ^~ /static/ {
alias /var/www/static/;
expires 30d;
}
# Regex eslesme (buyuk/kucuk harf duyarli)
location ~ \.php$ {
# PHP-FPM yapilandirmasi
}
# Regex eslesme (buyuk/kucuk harf duyarsiz)
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 365d;
add_header Cache-Control "public, immutable";
}
# Genel prefix eslesme
location / {
try_files $uri $uri/ /index.html;
}
# location oncelik sirasi:
# 1. = (tam eslesme)
# 2. ^~ (oncelikli prefix)
# 3. ~ veya ~* (regex)
# 4. / (genel prefix)
}Reverse Proxy (Ters Vekil Sunucu)
Nginx'in en yaygın kullanımı, arka plandaki uygulama sunucularına istek yönlendirmektir.
Node.js (Express / Fastify / Next.js)
# /etc/nginx/sites-available/nodeapp.com
server {
listen 80;
server_name nodeapp.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
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;
# Baglanti zaman asimlari
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
}Laravel (PHP-FPM)
# /etc/nginx/sites-available/laravel.com
server {
listen 80;
server_name laravel.com;
root /var/www/laravel/public;
index index.php index.html;
# Laravel icin guzel URL'ler
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# PHP-FPM'e yonlendir
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.3-fpm.sock;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_connect_timeout 60s;
fastcgi_send_timeout 120s;
fastcgi_read_timeout 120s;
# Buyuk dosya yukleme
client_max_body_size 64m;
}
# Hassas dosyalari engelle
location ~ /\.(?!well-known) {
deny all;
}
location ~ \.(env|log|git) {
deny all;
}
}Django (Gunicorn)
# /etc/nginx/sites-available/django.com
server {
listen 80;
server_name django.com;
# Static dosyalar (collectstatic ciktisi)
location /static/ {
alias /var/www/django/staticfiles/;
expires 30d;
add_header Cache-Control "public";
}
# Media dosyalari (kullanici yuklemeleri)
location /media/ {
alias /var/www/django/media/;
expires 7d;
}
# Gunicorn'a yonlendir
location / {
proxy_pass http://unix:/run/gunicorn/django.sock;
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;
}
}ASP.NET (Kestrel)
# /etc/nginx/sites-available/dotnet.com
server {
listen 80;
server_name dotnet.com;
location / {
proxy_pass http://127.0.0.1:5000;
proxy_http_version 1.1;
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;
# ASP.NET icin buyuk header destegi
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
}
}WebSocket Proxy (WebSocket Vekil)
# WebSocket destegi (ornegin Socket.io, SignalR)
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 80;
server_name ws.ornek.com;
# Normal HTTP istekleri
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# WebSocket endpoint
location /ws {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
# WebSocket baglantilari uzun sureli olabilir
proxy_read_timeout 86400s;
proxy_send_timeout 86400s;
}
}Çoklu Servis (Microservices)
server {
listen 80;
server_name api.ornek.com;
# Kullanici servisi
location /api/users {
proxy_pass http://127.0.0.1:3001;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# Siparis servisi
location /api/orders {
proxy_pass http://127.0.0.1:3002;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# Bildirim servisi
location /api/notifications {
proxy_pass http://127.0.0.1:3003;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}SSL / TLS (HTTPS - Secure Connection)
Let's Encrypt + Certbot (Free SSL Certificates)
# Certbot kur (Ubuntu)
sudo apt install certbot python3-certbot-nginx -y
# Sertifika al ve Nginx'i otomatik yapilandir
sudo certbot --nginx -d ornek.com -d www.ornek.com
# Sadece sertifika al (manuel yapilandirma icin)
sudo certbot certonly --webroot -w /var/www/ornek.com/public \
-d ornek.com -d www.ornek.com
# Otomatik yenilemeyi test et
sudo certbot renew --dry-runCertbot otomatik olarak cron/systemd timer ekler. Manuel kontrol:
# Yenileme zamanlayicisi
sudo systemctl status certbot.timer
# Manuel yenileme
sudo certbot renewSSL Server Block Örneği (SSL Server Block Example)
# HTTP -> HTTPS yonlendirme
server {
listen 80;
listen [::]:80;
server_name ornek.com www.ornek.com;
return 301 https://$server_name$request_uri;
}
# HTTPS server block
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name ornek.com www.ornek.com;
# SSL sertifikalari
ssl_certificate /etc/letsencrypt/live/ornek.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/ornek.com/privkey.pem;
# SSL ayarlari (guvenli varsayilanlar)
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
# SSL oturum onbellegi
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_session_tickets off;
# OCSP Stapling
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
# HSTS (ilk etkinlestirmede max-age'i dusuk tut, sorun yoksa artir)
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
root /var/www/ornek.com/public;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}SSL Snippet (Tekrar Kullanılabilir / Reusable SSL Configuration)
# /etc/nginx/snippets/ssl-params.conf
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_session_tickets off;
ssl_stapling on;
ssl_stapling_verify on;# Kullanim
server {
listen 443 ssl http2;
ssl_certificate /etc/letsencrypt/live/ornek.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/ornek.com/privkey.pem;
include snippets/ssl-params.conf;
# ...
}Performans (Performance)
Load Balancing (Yük Dengeleme)
# Upstream tanimlama
upstream backend_servers {
# Round-robin (varsayilan) -- istekleri sirayla dagitir
server 127.0.0.1:3001;
server 127.0.0.1:3002;
server 127.0.0.1:3003;
}
# Agirlikli dagitim (weighted)
upstream backend_weighted {
server 127.0.0.1:3001 weight=3; # Isteklerin %60'i
server 127.0.0.1:3002 weight=1; # Isteklerin %20'si
server 127.0.0.1:3003 weight=1; # Isteklerin %20'si
}
# En az baglanti (least connections)
upstream backend_least {
least_conn;
server 127.0.0.1:3001;
server 127.0.0.1:3002;
server 127.0.0.1:3003;
}
# IP Hash (ayni IP her zaman ayni sunucuya gider -- oturum tutarliligi)
upstream backend_sticky {
ip_hash;
server 127.0.0.1:3001;
server 127.0.0.1:3002;
server 127.0.0.1:3003;
}
# Yedek sunucu ve saglik kontrolu
upstream backend_ha {
server 127.0.0.1:3001;
server 127.0.0.1:3002;
server 127.0.0.1:3003 backup; # Sadece digerleri cokerse
server 127.0.0.1:3004 down; # Gecici devre disi
# Basarisiz denemelerden sonra sunucuyu devre disi birak
# 3 hata sonrasi 30 saniye bekle
}
server {
listen 80;
server_name ornek.com;
location / {
proxy_pass http://backend_servers;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
# Basarisiz sunucuyu atla
proxy_next_upstream error timeout http_502 http_503;
proxy_next_upstream_timeout 10s;
proxy_next_upstream_tries 3;
}
}Static Dosya Önbellekleme (Static File Caching)
# Static dosyalar icin cache header'lari
location ~* \.(jpg|jpeg|png|gif|ico|webp|avif)$ {
expires 365d;
add_header Cache-Control "public, immutable";
access_log off;
}
location ~* \.(css|js)$ {
expires 30d;
add_header Cache-Control "public";
access_log off;
}
location ~* \.(woff|woff2|ttf|otf|eot)$ {
expires 365d;
add_header Cache-Control "public, immutable";
add_header Access-Control-Allow-Origin "*";
access_log off;
}
location ~* \.(pdf|doc|docx)$ {
expires 7d;
add_header Cache-Control "public";
}Gzip Sıkıştırma (Gzip Compression)
# nginx.conf icinde http blogu altina
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 5; # 1-9 arasi, 5 iyi denge
gzip_min_length 1024; # 1KB'den kucuk dosyalari sikistirma
gzip_types
text/plain
text/css
text/javascript
application/json
application/javascript
application/xml
application/xml+rss
image/svg+xml
font/woff2;Brotli Sıkıştırma (Brotli Compression)
Brotli, gzip'ten daha iyi sıkıştırma oranı sağlar. Nginx'e modül olarak eklenir:
# Ubuntu icin brotli modulu
sudo apt install libnginx-mod-brotli -y# Brotli yapilandirmasi
brotli on;
brotli_comp_level 6; # 0-11 arasi
brotli_types
text/plain
text/css
text/javascript
application/json
application/javascript
application/xml
image/svg+xml
font/woff2;Proxy Önbelleği (Proxy Cache)
# Proxy cache tanimlama (http blogu icinde)
proxy_cache_path /var/cache/nginx levels=1:2
keys_zone=app_cache:10m
max_size=1g
inactive=60m
use_temp_path=off;
server {
location / {
proxy_pass http://backend_servers;
proxy_cache app_cache;
proxy_cache_valid 200 10m; # 200 OK icin 10 dk
proxy_cache_valid 404 1m; # 404 icin 1 dk
proxy_cache_use_stale error timeout updating
http_500 http_502 http_503;
# Cache durumunu header olarak ekle (debug icin)
add_header X-Cache-Status $upstream_cache_status;
}
# Cache'i atla (ornegin admin paneli)
location /admin {
proxy_pass http://backend_servers;
proxy_cache off;
}
}Güvenlik (Security)
Rate Limiting (İstek Hız Sınırlama)
# Rate limit tanimlama (http blogu icinde)
# Ayni IP'den saniyede 10 istek
limit_req_zone $binary_remote_addr zone=genel:10m rate=10r/s;
# Login sayfasi icin daha siki limit
limit_req_zone $binary_remote_addr zone=login:10m rate=1r/s;
# API icin limit
limit_req_zone $binary_remote_addr zone=api:10m rate=30r/s;
server {
# Genel rate limit (burst ile ani yuk tolere et)
location / {
limit_req zone=genel burst=20 nodelay;
limit_req_status 429;
proxy_pass http://backend_servers;
}
# Login icin siki limit
location /api/login {
limit_req zone=login burst=5;
limit_req_status 429;
proxy_pass http://backend_servers;
}
# API icin orta seviye limit
location /api/ {
limit_req zone=api burst=50 nodelay;
limit_req_status 429;
proxy_pass http://backend_servers;
}
}Güvenlik Header'ları (Security Headers)
# /etc/nginx/snippets/security-headers.conf
# XSS korumasini etkinlestir
add_header X-Content-Type-Options "nosniff" always;
# Clickjacking korumasini etkinlestir
add_header X-Frame-Options "SAMEORIGIN" always;
# XSS filtre
add_header X-XSS-Protection "1; mode=block" always;
# Referer politikasi
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# Content Security Policy (projenize gore duzenleyin)
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' https://fonts.gstatic.com" always;
# Izin politikasi
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;# Server block icinde kullanim
server {
include snippets/security-headers.conf;
# ...
}IP Whitelist / Blacklist (IP İzin / Engel Listesi)
# Belirli IP'lere erisim izni (whitelist)
location /admin {
allow 192.168.1.0/24; # Yerel ag
allow 10.0.0.50; # Belirli IP
deny all; # Geri kalan herkes engellenir
proxy_pass http://backend_servers;
}
# Belirli IP'leri engelle (blacklist)
location / {
deny 203.0.113.0/24; # Bu araligi engelle
deny 198.51.100.5; # Bu IP'yi engelle
allow all; # Geri kalan herkese izin ver
proxy_pass http://backend_servers;
}
# Geo-bazli erisim kontrolu (GeoIP modulu gerekir)
# geoip_country /usr/share/GeoIP/GeoIP.dat;
# if ($geoip_country_code = "XX") { return 403; }Hassas Dosyaları Engelleme (Block Sensitive Files)
# Gizli dosyalar (.env, .git, .htaccess vb.)
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
# Yedek ve yapilandirma dosyalari
location ~* \.(bak|config|sql|fla|psd|ini|log|sh|inc|swp|dist)$ {
deny all;
}
# Source map dosyalarini production'da engelle
location ~* \.map$ {
deny all;
}DDoS Korumaları (DDoS Protection)
# Baglanti limiti (http blogu icinde)
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
# IP basina max 100 es zamanli baglanti
limit_conn addr 100;
# Istemci govde boyutunu sinirla
client_max_body_size 10m;
# Yavas istemcileri kes
client_body_timeout 10s;
client_header_timeout 10s;
send_timeout 10s;
# Buffer boyutlarini sinirla (buffer overflow onlemi)
client_body_buffer_size 1k;
client_header_buffer_size 1k;
large_client_header_buffers 2 1k;
# Sunucu versiyonunu gizle
server_tokens off;
}Loglama (Logging)
Log Formatları (Log Formats)
# Standart format
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
# JSON format (log toplama araclari icin -- ELK, Loki vb.)
log_format json_log escape=json
'{'
'"time":"$time_iso8601",'
'"remote_addr":"$remote_addr",'
'"request":"$request",'
'"status":$status,'
'"body_bytes_sent":$body_bytes_sent,'
'"request_time":$request_time,'
'"upstream_response_time":"$upstream_response_time",'
'"http_referer":"$http_referer",'
'"http_user_agent":"$http_user_agent"'
'}';
# Performans analizi icin
log_format performance '$remote_addr - [$time_local] '
'"$request" $status '
'rt=$request_time '
'urt=$upstream_response_time '
'cs=$upstream_cache_status';Log Yönetimi (Log Management)
server {
# Site bazli log
access_log /var/log/nginx/ornek.com.access.log main;
error_log /var/log/nginx/ornek.com.error.log warn;
# Static dosyalar icin loglama kapat (disk I/O azalt)
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2)$ {
access_log off;
}
# Saglik kontrolu icin loglama kapat
location = /health {
access_log off;
return 200 "OK";
}
}# Log rotasyonu (/etc/logrotate.d/nginx)
# Varsayilan olarak kurulur, ozellestirilabilir:
# Canli log izleme
tail -f /var/log/nginx/access.log
# Hata loglarini izle
tail -f /var/log/nginx/error.log
# En cok istek yapan IP'ler
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20
# En cok 404 alan URL'ler
awk '$9 == 404 {print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20
# Yavas istekler (request_time performance log'undan)
awk -F'rt=' '$2+0 > 1.0 {print}' /var/log/nginx/performance.logPratik İpuçları (Practical Tips)
Yapılandırma Kontrol Listesi (Configuration Checklist)
Yeni bir site yapılandırırken aşağıdaki adımları takip edin:
nginx -tile config'i her değişiklikten sonra test edin- HTTP'den HTTPS'e yönlendirme ekleyin
server_tokens offile Nginx versiyonunu gizleyin- Güvenlik header'larını ekleyin
- Rate limiting yapılandırın
- Gzip/Brotli sıkıştırma etkinleştirin
- Static dosyalar için cache header'ları ayarlayın
- Log rotasyonunu kontrol edin
- SSL Labs testi yapın:
https://www.ssllabs.com/ssltest/
SPA (Single Page Application) Yapılandırması (SPA Configuration)
server {
listen 80;
server_name spa.ornek.com;
root /var/www/spa/dist;
# Tum rotalari index.html'e yonlendir (client-side routing)
location / {
try_files $uri $uri/ /index.html;
}
# API isteklerini backend'e yonlendir
location /api/ {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# Hashed asset'ler icin uzun cache
location ~* \.[a-f0-9]{8,}\.(js|css)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# index.html cache'lenmemeli (her zaman guncel versiyon)
location = /index.html {
add_header Cache-Control "no-cache, no-store, must-revalidate";
}
}Yaygın Hatalar ve Çözümleri (Common Errors & Solutions)
| Hata | Neden | Çözüm |
|---|---|---|
| 502 Bad Gateway | Backend sunucu cevap vermiyor | Backend servisinin çalıştığını kontrol et |
| 504 Gateway Timeout | Backend çok yavaş | proxy_read_timeout değerini artır |
| 413 Entity Too Large | Dosya boyutu limiti | client_max_body_size değerini artır |
| 403 Forbidden | Dosya izin hatası | chown www-data:www-data ve izinleri kontrol et |
| Config test failed | Söz dizimi hatası | nginx -t çıktısında belirtilen satırı kontrol et |
Faydalı Değişkenler (Useful Variables)
# Sik kullanilan Nginx degiskenleri
# $host -- Istek host header'i
# $remote_addr -- Istemci IP adresi
# $request_uri -- Tam istek URI'si (query string dahil)
# $uri -- Normalize edilmis URI
# $args -- Query string parametreleri
# $scheme -- http veya https
# $request_method -- GET, POST, PUT, DELETE vb.
# $server_name -- Server name directive degeri
# $content_type -- Content-Type header'i
# $http_HEADER -- Herhangi bir istek header'i (- yerine _ kullan)Debugging (Hata Ayıklama)
# Detayli config test
nginx -T # Tum yapilandirmayi goster
# Debug seviyesinde hata logu
error_log /var/log/nginx/error.log debug;
# Belirli bir IP icin debug (uretimde kullanisli)
events {
debug_connection 192.168.1.100;
}
# Aktif baglanti sayisini goster
location /nginx_status {
stub_status on;
allow 127.0.0.1;
deny all;
}İlgili Rehberler (Related Guides)
DevOps & Tools (DevOps ve Araçlar)
- DevOps Genel Bakış
- Git Notları
- Docker Rehberi
- Kubernetes
- Linux CLI
- Deployment & Hosting
- Ubuntu Rehberi
- VS Code Rehberi
- Regex Rehberi