บทนำ
การตั้งค่า Nginx ร่วมกับ Let’s Encrypt เป็นวิธีที่มีประสิทธิภาพในการสร้าง SSL Certificate อัตโนมัติ นิยมใช้ Certbot Nginx Plugin เพื่อจัดการ HTTPS และ Redirect HTTP ไปยัง HTTPS แบบอัตโนมัติ ซึ่งเป็นมาตรฐานสำหรับการรักษาความปลอดภัยของเว็บไซต์สมัยใหม่
ติดตั้ง Certbot และ Nginx Plugin
ก่อนอื่น เราต้องติดตั้ง Certbot พร้อมกับ Nginx Plugin:
sudo apt update
sudo apt install -y certbot python3-certbot-nginx
สร้างและตั้งค่า SSL Certificate บน Nginx
ใช้ Certbot เพื่อสร้าง SSL Certificate ใหม่และเปิดใช้งาน Auto HTTPS Redirect:
sudo certbot --nginx -d example.com -d www.example.com
Certbot จะถามคุณหลายข้อมูล และสร้าง Temporary Web Server เพื่อตรวจสอบ ACME Challenge ที่ใช้ยืนยันความเป็นเจ้าของโดเมน
การตั้งค่า SSL Protocols และ Ciphers
ตั้งค่า ssl_protocols เพื่อใช้เฉพาะโปรโตคอล TLS ที่มีความปลอดภัยสูง:
server {
listen 443 ssl;
server_name example.com www.example.com;
# SSL Certificate
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# Protocols
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
# HSTS
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
root /var/www/example.com;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
# HTTP Redirect to HTTPS
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$server_name$request_uri;
}
Certbot Auto-Renewal
Let’s Encrypt Certificate มีอายุ 90 วัน Certbot จะติดตั้ง Cron Job เพื่อต่ออายุ Certificate โดยอัตโนมัติ:
sudo certbot renew --dry-run
Systemd Timer จะดูแล Auto-Renewal สองครั้งต่อวัน ดังนั้นคุณไม่ต้องกังวลเรื่องการต่ออายุด้วยตัวเอง
HSTS – HTTP Strict Transport Security
ตั้งค่า HSTS Header เพื่อปกป้องผู้ใช้จากการ Man-in-the-Middle Attack:
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
ทดสอบการตั้งค่า Nginx
ตรวจสอบไฟล์การตั้งค่า Nginx และรีสตาร์ท:
sudo nginx -t
sudo systemctl restart nginx
ตรวจสอบ SSL Certificate
คุณสามารถตรวจสอบการตั้งค่า SSL ของคุณโดยใช้เว็บไซต์เช่น SSL Shopper หรืออื่นๆ เพื่อให้มั่นใจว่า Certificate และการตั้งค่า SSL นั้นถูกต้อง
Nginx SSL Certificate Pinning (ไม่จำเป็น)
หากต้องการการรักษาความปลอดภัยเพิ่มเติม คุณสามารถใช้ Certificate Pinning:
add_header Public-Key-Pins 'pin-sha256="..."; pin-sha256="..."; max-age=31536000' always;
