🌐 Nginx
高效能的 HTTP 伺服器與反向代理
Nginx 以事件驅動架構著稱,高並發下記憶體佔用極低,是全球最廣泛使用的 Web 伺服器之一,也常作反向代理與靜態檔案伺服器。
安裝
$ sudo apt update && sudo apt install -y nginx$ sudo systemctl enable --now nginxCreated symlink /etc/systemd/system/multi-user.target.wants/nginx.service
安裝後瀏覽器開啟 http://你的伺服器IP 應可看到 Nginx 預設歡迎頁。
設定檔結構
/etc/nginx/
├── nginx.conf # 主設定檔(worker、日誌等全域設定)
├── conf.d/ # 額外設定(drop-in)
├── sites-available/ # 虛擬主機設定檔(撰寫於此)
├── sites-enabled/ # 啟用的虛擬主機(symlink 到 sites-available)
├── snippets/ # 可重複引用的設定片段
└── mime.types # MIME 類型對應
修改設定後,先用
sudo nginx -t 測試語法,再 sudo systemctl reload nginx 重新載入,不會中斷現有連線。
虛擬主機設定(Static Site)
$ sudo vim /etc/nginx/sites-available/example.comserver {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
root /var/www/example.com;
index index.html index.php;
# 靜態檔案快取
location ~* \.(js|css|png|jpg|ico|webp)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
# 404 頁面
error_page 404 /404.html;
# 日誌
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log;
}$ sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx反向代理(Node.js / Python 應用)
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://127.0.0.1:3000; # 後端應用 port
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;
}
}常用操作指令
| 操作 | 指令 |
|---|---|
| 測試設定語法 | sudo nginx -t |
| 重新載入設定(不中斷) | sudo systemctl reload nginx |
| 完全重啟 | sudo systemctl restart nginx |
| 查看狀態與錯誤 | sudo systemctl status nginx |
| 即時追蹤存取日誌 | sudo tail -f /var/log/nginx/access.log |
| 即時追蹤錯誤日誌 | sudo tail -f /var/log/nginx/error.log |
| 查看監聽 port | sudo ss -tlnp | grep nginx |
搭配 Let's Encrypt SSL
$ sudo apt install -y certbot python3-certbot-nginx$ sudo certbot --nginx -d example.com -d www.example.comCertbot 會自動修改你的 Nginx 設定,新增 HTTPS 監聽並設定憑證路徑。詳見 Certbot 設定教學。
常見問題
✕ 403 Forbidden
- 原因
- root 目錄權限不足,或 index 檔案不存在。
- 解法
sudo chmod 755 /var/www/example.com,確認 index.html 存在,並確認 Nginx 程序使用者(www-data)有讀取權限。
✕ 502 Bad Gateway(反向代理)
- 原因
- 後端應用未啟動,或 proxy_pass 的 port 錯誤。
- 解法
- 確認後端服務正在執行:
ss -tlnp | grep 3000,再查看錯誤日誌:tail -f /var/log/nginx/error.log。
✕ nginx: [emerg] bind() to 0.0.0.0:80 failed
- 原因
- 80 port 已被其他程序佔用。
- 解法
sudo ss -tlnp | grep :80找出佔用程序並停止,再啟動 Nginx。