สารบัญ
- 1. Nginx คืออะไรและทำไมต้องตั้งค่าขั้นสูง
- 2. ติดตั้ง Nginx และโครงสร้างไฟล์
- 3. ตั้งค่า Virtual Host หลายโดเมน
- 4. ตั้งค่า SSL/TLS บน Nginx
- 5. เปิดใช้งาน Gzip Compression
- 6. ตั้งค่า Security Headers
- 7. Rate Limiting และ Connection Limiting
- 8. Caching และ Reverse Proxy
- 9. Optimize Nginx สำหรับ WordPress
- 10. ตรวจสอบและ Debug Nginx
- FAQ
Nginx คืออะไรและทำไมต้องตั้งค่าขั้นสูง
Nginx (อ่านว่า Engine-X) คือ Web Server ที่ได้รับความนิยมสูงสุดในโลกในปี 2026 ด้วยการออกแบบที่ใช้ Event-driven, Non-blocking I/O ทำให้สามารถรองรับ connection พร้อมกันได้หลายหมื่นตัวโดยใช้ทรัพยากรน้อยกว่า Apache มาก
การติดตั้ง Nginx แบบพื้นฐานด้วย apt install nginx นั้นเพียงพอสำหรับทดสอบ แต่ในระบบ Production บน VPS จริงๆ คุณต้องตั้งค่าให้เหมาะสมกับโหลดจริงและความปลอดภัยที่ต้องการ
| ฟีเจอร์ | Default Config | Optimized Config |
|---|---|---|
| Worker Processes | 1 | = จำนวน CPU cores |
| Worker Connections | 768 | 1024–65535 |
| Gzip | ปิด | เปิด, level 5 |
| SSL Protocols | TLSv1 TLSv1.1 TLSv1.2 | TLSv1.2 TLSv1.3 เท่านั้น |
| Security Headers | ไม่มี | HSTS, CSP, X-Frame-Options |
| Rate Limiting | ไม่มี | จำกัด req/s ต่อ IP |
| FastCGI Cache | ปิด | เปิด สำหรับ WordPress |
ติดตั้ง Nginx และโครงสร้างไฟล์
เริ่มต้นด้วยการติดตั้ง Nginx บน Ubuntu 22.04/24.04 LTS:
sudo apt update && sudo apt install nginx -y sudo systemctl enable nginx sudo systemctl start nginx
โครงสร้างไฟล์ Nginx
/etc/nginx/nginx.conf— ไฟล์ config หลัก (global settings)/etc/nginx/sites-available/— ไฟล์ server block แต่ละโดเมน/etc/nginx/sites-enabled/— symlink ไฟล์ที่ active/etc/nginx/conf.d/— config เสริม (snippets)/var/log/nginx/access.log— access log/var/log/nginx/error.log— error log/var/www/html/— web root default
ตั้งค่า nginx.conf หลัก
user www-data;
worker_processes auto; # ใช้ CPU ทุก core อัตโนมัติ
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
events {
worker_connections 1024;
multi_accept on;
use epoll;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
server_tokens off; # ซ่อน Nginx version
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Logging
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
# Gzip (ดูรายละเอียดในหัวข้อ Gzip)
gzip on;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
เคล็ดลับ: server_tokens off สำคัญมากสำหรับความปลอดภัย เพราะซ่อนเวอร์ชัน Nginx ไม่ให้ attacker รู้ว่าเราใช้เวอร์ชันใดและค้นหา exploit ที่ตรงกันได้
ตั้งค่า Virtual Host (Server Block) หลายโดเมน
Nginx เรียก Virtual Host ว่า Server Block เราสามารถรองรับหลายโดเมนบน IP เดียวได้ด้วย SNI (Server Name Indication)
สร้าง Server Block สำหรับโดเมนใหม่
sudo nano /etc/nginx/sites-available/example.com
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
root /var/www/example.com/public;
index index.php index.html index.htm;
# PHP-FPM
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
# Deny .htaccess
location ~ /\.ht {
deny all;
}
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log;
}
# เปิดใช้งาน Server Block sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ sudo nginx -t # ทดสอบ config sudo nginx -s reload
โครงสร้าง Web Root
sudo mkdir -p /var/www/example.com/public sudo chown -R www-data:www-data /var/www/example.com sudo chmod -R 755 /var/www/example.com
ตั้งค่า SSL/TLS บน Nginx
ในปี 2026 SSL เป็นสิ่งจำเป็นสำหรับทุกเว็บไซต์ทั้งด้านความปลอดภัยและ SEO บน VPS เราสามารถใช้ Let's Encrypt SSL ฟรีได้ด้วย Certbot
ติดตั้ง Certbot และออก SSL
sudo apt install certbot python3-certbot-nginx -y sudo certbot --nginx -d example.com -d www.example.com
ตั้งค่า SSL แบบ Manual (Hardened)
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# TLS Protocols — เฉพาะ 1.2 และ 1.3
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers off;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
# OCSP Stapling
ssl_stapling on;
ssl_stapling_verify on;
resolver 1.1.1.1 8.8.8.8 valid=300s;
# SSL Session Cache
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_session_tickets off;
root /var/www/example.com/public;
# ... ส่วนอื่นๆ ของ config
}
# Redirect HTTP → HTTPS
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}
⚠️ สำคัญ: ห้ามใช้ TLSv1 และ TLSv1.1 บน Production เพราะมีช่องโหว่ที่ถูก exploit แล้ว ใช้เฉพาะ TLSv1.2 และ TLSv1.3 เท่านั้น สามารถตรวจสอบ SSL grade ได้ที่ SSL Labs
เปิดใช้งาน Gzip Compression
Gzip ลดขนาดไฟล์ที่ส่งออกได้ถึง 60-80% ทำให้หน้าเว็บโหลดเร็วขึ้นอย่างเห็นได้ชัด เพิ่ม config ใน http {} block ของ nginx.conf:
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 5; # ระดับ 1-9 (5 = balance ระหว่าง CPU กับ compression ratio)
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_min_length 256; # ไม่ compress ไฟล์เล็กกว่า 256 bytes
gzip_types
application/atom+xml
application/geo+json
application/javascript
application/x-javascript
application/json
application/ld+json
application/manifest+json
application/rdf+xml
application/rss+xml
application/xhtml+xml
application/xml
font/eot
font/otf
font/ttf
image/svg+xml
text/css
text/javascript
text/plain
text/xml;
หมายเหตุ: ไม่ต้อง Gzip ไฟล์ที่บีบอัดแล้วอย่าง JPEG, PNG, WebP, GIF, ZIP, MP4 เพราะไม่ได้ประโยชน์และเพิ่มภาระ CPU โดยเปล่าประโยชน์
ตั้งค่า Security Headers
Security Headers บน Nginx ช่วยป้องกันการโจมตีประเภทต่างๆ เพิ่ม config ใน server block ที่ต้องการ:
add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; add_header Referrer-Policy "no-referrer-when-downgrade" always; add_header X-XSS-Protection "1; mode=block" always; add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always; # HSTS (เปิดหลังจาก SSL ทำงานแล้วอย่างน้อย 1 สัปดาห์) add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
| Header | ป้องกัน |
|---|---|
| X-Frame-Options: SAMEORIGIN | Clickjacking attacks |
| X-Content-Type-Options: nosniff | MIME-type sniffing |
| Referrer-Policy | Information leakage |
| X-XSS-Protection | Reflected XSS (legacy browsers) |
| HSTS | SSL stripping, man-in-the-middle |
| Permissions-Policy | Unauthorized API access |
Rate Limiting และ Connection Limiting
Rate Limiting จำกัดจำนวน request จาก IP เดียวกัน ป้องกัน DDoS และ brute force login:
# เพิ่มใน http {} block ของ nginx.conf
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=1r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;
# เพิ่มใน server {} หรือ location {} block
# สำหรับ WordPress Login
location = /wp-login.php {
limit_req zone=login burst=3 nodelay;
limit_conn addr 3;
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
}
# สำหรับ API endpoint ทั่วไป
location /api/ {
limit_req zone=api burst=20 nodelay;
proxy_pass http://backend;
}
Caching และ Reverse Proxy
Nginx FastCGI Cache เก็บผลลัพธ์จาก PHP ไว้ใน disk ทำให้ request ครั้งถัดไปไม่ต้องรัน PHP ใหม่ เร็วขึ้น 10-50 เท่า:
# เพิ่มใน http {} block
fastcgi_cache_path /tmp/nginx-cache levels=1:2 keys_zone=WORDPRESS:100m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
# เพิ่มใน server {} block
set $skip_cache 0;
# ไม่ cache: POST requests, URL มี query string, logged-in users
if ($request_method = POST) { set $skip_cache 1; }
if ($query_string != "") { set $skip_cache 1; }
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_logged_in") {
set $skip_cache 1;
}
location ~ \.php$ {
fastcgi_cache WORDPRESS;
fastcgi_cache_valid 200 60m;
fastcgi_cache_bypass $skip_cache;
fastcgi_no_cache $skip_cache;
add_header X-FastCGI-Cache $upstream_cache_status;
# ... fastcgi_pass etc.
}
Reverse Proxy สำหรับ Node.js / Python App
server {
listen 443 ssl http2;
server_name app.example.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
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_bypass $http_upgrade;
proxy_read_timeout 90;
}
}
Optimize Nginx สำหรับ WordPress
WordPress บน Nginx ต้องตั้งค่าพิเศษเพราะไม่รองรับ .htaccess ต้องใช้ try_files แทน:
server {
listen 443 ssl http2;
server_name myblog.com www.myblog.com;
root /var/www/myblog.com/public;
index index.php;
# WordPress Permalink
location / {
try_files $uri $uri/ /index.php?$args;
}
# ป้องกัน Direct access ไฟล์ sensitive
location ~* /(?:uploads|files)/.*\.php$ { deny all; }
location = /xmlrpc.php { deny all; }
location ~* /wp-includes/.*\.php$ {
internal;
}
# Static files cache (Browser Caching)
location ~* \.(css|js|png|jpg|jpeg|gif|webp|ico|svg|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
access_log off;
}
# PHP
location ~ \.php$ {
try_files $uri =404;
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
fastcgi_param HTTP_PROXY "";
}
location ~ /\.ht { deny all; }
}
ตรวจสอบและ Debug Nginx Configuration
ก่อน reload หรือ restart Nginx ทุกครั้งควรทดสอบ config ก่อนเสมอ:
# ทดสอบ syntax sudo nginx -t # ผลที่ต้องการ: # nginx: the configuration file /etc/nginx/nginx.conf syntax is ok # nginx: configuration file /etc/nginx/nginx.conf test is successful # Reload (ไม่หยุด service) sudo nginx -s reload # หรือใช้ systemd sudo systemctl reload nginx
ดู Log แบบ Real-time
# Access log sudo tail -f /var/log/nginx/access.log # Error log (สำคัญมากเมื่อเว็บมีปัญหา) sudo tail -f /var/log/nginx/error.log # Log เฉพาะโดเมน sudo tail -f /var/log/nginx/example.com.error.log
เช็ค Status และ Connections
# เปิด stub_status ใน config
location /nginx_status {
stub_status;
allow 127.0.0.1;
deny all;
}
# ดู status
curl http://127.0.0.1/nginx_status
สรุปสิ่งที่ต้องทำสำหรับ Nginx Production
- ตั้ง
worker_processes autoและserver_tokens offใน nginx.conf - สร้าง Server Block แยกสำหรับแต่ละโดเมนใน sites-available/
- ติดตั้ง Let's Encrypt SSL และบังคับ HTTPS ด้วย 301 redirect
- เปิด Gzip สำหรับ text, CSS, JS และ SVG
- เพิ่ม Security Headers: HSTS, X-Frame-Options, X-Content-Type-Options
- ตั้ง Rate Limiting สำหรับ /wp-login.php และ API endpoints
- เปิด FastCGI Cache สำหรับ WordPress เพิ่มความเร็ว
- รัน
nginx -tก่อน reload ทุกครั้ง
คำถามที่พบบ่อย (FAQ)
sudo nginx -t เพื่อทดสอบ syntax ทั้งหมด ถ้าไม่มี error จะขึ้น "syntax is ok" และ "test is successful" จากนั้น sudo nginx -s reload เพื่อ reload โดยไม่ต้องหยุด service หาก config ผิดพลาด Nginx จะไม่ reload และเว็บยังทำงานต่อได้ตามปกติlimit_req_zone ใน http block และ limit_req ใน location block เช่น limit 10 request/second ต่อ IP ถือเป็น security baseline ที่ควรมีทุก production serverต้องการ VPS สำหรับรัน Nginx?
AsiaGB มี VPS Thailand และ Singapore พร้อม SSD เร็ว Uptime 99% รองรับ Ubuntu 22.04/24.04 ติดตั้ง Nginx ได้ทันที
ดู VPS แพ็กเกจ →