nginx
sudo systemctl start nginx
nginx -s stop
nginx -s quit
sudo systemctl stop nginx
nginx -s reload
sudo systemctl reload nginx
nginx -s reopen
sudo systemctl restart nginx
nginx -t
nginx -T
nginx -t -c /path/to/nginx.conf
nginx -t -c /etc/nginx/sites-available/example.conf
nginx -v
nginx -V
ps aux | grep nginx
sudo ss -tlnp | grep nginx
sudo netstat -tlnp | grep nginx
sudo systemctl status nginx
| 參數 |
說明 |
範例 |
-t |
測試設定檔語法 |
nginx -t |
-T |
測試並輸出完整設定 |
nginx -T |
-c |
指定設定檔路徑 |
nginx -c /path/to/nginx.conf |
-s |
發送信號給主程序 |
nginx -s reload |
-p |
設定 prefix 路徑 |
nginx -p /var/nginx |
-g |
設定全域指令 |
nginx -g "daemon off;" |
-v |
顯示版本 |
nginx -v |
-V |
顯示版本和編譯資訊 |
nginx -V |
-q |
安靜模式(只顯示錯誤) |
nginx -t -q |
| 信號 |
說明 |
使用情境 |
stop |
快速停止 |
立即終止所有連線 |
quit |
優雅停止 |
等待現有請求完成後停止 |
reload |
重新載入設定 |
修改設定後套用(不中斷服務)⭐ |
reopen |
重新開啟日誌 |
log rotation 後使用 |
sudo vim /etc/nginx/sites-available/example.conf
sudo nginx -t
sudo nginx -s reload
sudo systemctl reload nginx
sudo ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/
sudo nginx -t && sudo nginx -s reload
sudo rm /etc/nginx/sites-enabled/example.conf
sudo nginx -t && sudo nginx -s reload
sudo tail -f /var/log/nginx/access.log
sudo tail -f /var/log/nginx/error.log
sudo tail -f /var/log/nginx/example.com.access.log
sudo grep "error" /var/log/nginx/error.log
sudo awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn
nginx -g "error_log /var/log/nginx/debug.log debug;"
events {
debug_connection 192.168.1.100;
}
/etc/nginx/nginx.conf
/etc/nginx/sites-available/
/etc/nginx/sites-enabled/
/etc/nginx/conf.d/
/etc/nginx/mime.types
/etc/nginx/fastcgi_params
/usr/local/etc/nginx/nginx.conf
/opt/homebrew/etc/nginx/nginx.conf
/usr/local/etc/nginx/servers/
/opt/homebrew/etc/nginx/servers/
docker run -d \
-v /path/to/nginx.conf:/etc/nginx/nginx.conf:ro \
-v /path/to/conf.d:/etc/nginx/conf.d:ro \
-p 80:80 \
nginx
docker run -d \
-v /path/to/html:/usr/share/nginx/html:ro \
-p 80:80 \
nginx
services:
nginx:
image: nginx:alpine
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
- ./conf.d:/etc/nginx/conf.d:ro
- ./html:/usr/share/nginx/html:ro
ports:
- "80:80"
| 路徑 |
說明 |
/etc/nginx/nginx.conf |
主設定檔 |
/etc/nginx/conf.d/ |
額外設定檔目錄(*.conf 自動載入) |
/etc/nginx/conf.d/default.conf |
預設站點設定 |
/usr/share/nginx/html/ |
預設網頁根目錄 |
/var/log/nginx/ |
日誌目錄 |
/var/cache/nginx/ |
快取目錄 |
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
}
}
server {
listen 80;
server_name another.com;
}
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
Nginx 設定檔由多個**區塊(Block/Context)**組成,每個區塊負責不同功能:
┌─────────────────────────────────────────────────────────────┐
│ main(全域) │
│ ├─ 程序層級設定:worker 數量、使用者、PID、錯誤日誌 │
│ │ │
│ ├─ events { } │
│ │ └─ 連線處理:最大連線數、事件模型 │
│ │ │
│ └─ http { } │
│ ├─ HTTP 全域設定:MIME、日誌、壓縮、快取 │
│ │ │
│ ├─ server { } ← 虛擬主機 1 │
│ │ ├─ 監聽 port、域名 │
│ │ └─ location { } ← URL 路徑處理 │
│ │ │
│ └─ server { } ← 虛擬主機 2 │
│ └─ ... │
└─────────────────────────────────────────────────────────────┘
| 區塊 |
層級 |
主要功能 |
| main |
最外層 |
Nginx 程序本身的設定(worker、使用者、日誌) |
| events |
main 內 |
連線處理機制(最大連線數、事件驅動模型) |
| http |
main 內 |
HTTP 服務全域設定(MIME、日誌格式、壓縮) |
| server |
http 內 |
虛擬主機設定(域名、port、SSL) |
| location |
server 內 |
URL 路徑匹配與處理規則 |
| upstream |
http 內 |
後端伺服器群組(負載平衡) |
功能:設定 Nginx 程序本身的行為,影響整個 Nginx 服務
user nginx nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
worker_rlimit_nofile 65535;
功能:設定 Nginx 如何處理網路連線(事件驅動模型)
events {
worker_connections 1024;
use epoll;
multi_accept on;
}
為什麼重要:
- Nginx 的高效能來自於非阻塞事件驅動架構
epoll(Linux)和 kqueue(macOS)是最高效的模型
worker_connections 決定能同時處理多少連線
功能:設定 HTTP 服務的全域行為,所有 server 區塊共享這些設定
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
gzip on;
gzip_types text/plain text/css application/json application/javascript;
server {
}
upstream backend {
server 192.168.1.101:3000;
server 192.168.1.102:3000;
}
include /etc/nginx/conf.d/*.conf;
}
http 區塊常見設定分類:
| 類別 |
設定項目 |
說明 |
| MIME |
include mime.types |
檔案類型對應 |
| 日誌 |
log_format, access_log |
存取日誌格式 |
| 效能 |
sendfile, tcp_nopush |
檔案傳輸優化 |
| 連線 |
keepalive_timeout |
持久連線設定 |
| 壓縮 |
gzip |
回應內容壓縮 |
| 快取 |
proxy_cache |
代理快取設定 |
server 區塊定義一個虛擬主機(Virtual Host)。
server {
listen 80;
listen [::]:80;
listen 443 ssl http2;
server_name example.com www.example.com;
root /var/www/example;
index index.html index.htm index.php;
}
server_name example.com;
server_name example.com www.example.com;
server_name *.example.com;
server_name example.*;
server_name ~^www\d+\.example\.com$;
server_name ~^(?<subdomain>.+)\.example\.com$;
server_name _;
server_name "";
- 精確名稱:
example.com
- 萬用字元開頭(最長優先):
*.example.com
- 萬用字元結尾(最長優先):
example.*
- 正則表達式(按設定檔順序):
~^www\d+\.example\.com$
- default_server:
listen 80 default_server;
listen 80;
listen 127.0.0.1:80;
listen 192.168.1.1:80;
listen [::]:80;
listen [::1]:80;
listen 80 default_server;
listen 443 ssl;
listen 443 ssl http2;
listen unix:/var/run/nginx.sock;
location /images/ {
root /var/www;
}
location /images/ {
alias /var/www/static/;
}
location 區塊定義如何處理特定 URI 的請求。
location [修飾符] 匹配模式 {
}
| 修飾符 |
說明 |
範例 |
| (無) |
前綴匹配 |
location /api/ |
= |
精確匹配 |
location = / |
~ |
區分大小寫的正則 |
location ~ \.php$ |
~* |
不區分大小寫的正則 |
location ~* \.(jpg|png)$ |
^~ |
前綴匹配,優先於正則 |
location ^~ /static/ |
location = / {
return 200 "Homepage";
}
location /api/ {
proxy_pass http://backend;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php-fpm.sock;
}
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
}
location ^~ /static/ {
root /var/www;
}
這是 Nginx 最重要的概念之一。
1. 檢查所有「精確匹配」(=)
├─ 找到 → 使用該 location,停止搜尋
└─ 未找到 → 繼續
2. 檢查所有「前綴匹配」(無修飾符 和 ^~)
├─ 記錄「最長匹配」的 location
├─ 如果最長匹配是 ^~ → 使用該 location,停止搜尋
└─ 否則 → 繼續
3. 按順序檢查「正則表達式」(~ 和 ~*)
├─ 找到第一個匹配 → 使用該 location,停止搜尋
└─ 全部未匹配 → 使用步驟 2 記錄的最長前綴匹配
1. = (精確匹配) - 最高優先
2. ^~ (前綴匹配,停止正則) - 第二優先
3. ~ 或 ~* (正則表達式) - 按設定順序,第一個匹配生效
4. 無修飾符 (前綴匹配) - 最長匹配生效
server {
listen 80;
server_name example.com;
location = / {
return 200 "Exact root";
}
location ^~ /static/ {
return 200 "Static files (prefix priority)";
}
location ~ \.html$ {
return 200 "HTML files (regex)";
}
location ~* \.(jpg|png)$ {
return 200 "Images (regex case-insensitive)";
}
location /api/ {
return 200 "API prefix";
}
location /api/v1/ {
return 200 "API v1 prefix (longer match)";
}
location / {
return 200 "Default";
}
}
| 請求 URI |
匹配的 location |
原因 |
/ |
= / |
精確匹配 |
/index.html |
~ \.html$ |
正則匹配 |
/static/style.css |
^~ /static/ |
^~ 前綴優先於正則 |
/static/logo.png |
^~ /static/ |
^~ 前綴優先於正則(不是 ~* 的 png) |
/images/logo.png |
~* \.(jpg|png)$ |
正則匹配 |
/api/users |
/api/ |
最長前綴匹配 |
/api/v1/users |
/api/v1/ |
最長前綴匹配 |
/about |
/ |
預設前綴匹配 |
location /admin/ {
allow 192.168.1.100;
allow 10.0.0.0/8;
deny all;
}
location /api/ {
deny 192.168.1.50;
allow 192.168.1.0/24;
deny all;
}
location /internal/ {
allow 10.0.0.0/8;
allow 172.16.0.0/12;
allow 192.168.0.0/16;
allow 127.0.0.1;
deny all;
}
location /admin/ {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
location /admin/ {
satisfy any;
allow 192.168.1.0/24;
deny all;
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
location /protected/ {
satisfy any;
allow 192.168.1.0/24;
deny all;
auth_basic "Protected";
auth_basic_user_file /etc/nginx/.htpasswd;
}
location /api/ {
limit_except GET HEAD {
deny all;
}
}
if ($request_method !~ ^(GET|POST)$) {
return 405;
}
location ~ /\. {
deny all;
return 404;
}
location ~* \.(git|svn|env|sql|log|bak)$ {
deny all;
return 404;
}
location ~* /(\.git|\.svn|\.env|node_modules)/ {
deny all;
return 404;
}
location ~* \.(jpg|jpeg|png|gif|webp)$ {
valid_referers none blocked server_names
*.example.com example.com;
if ($invalid_referer) {
return 403;
}
}
| 變數 |
說明 |
範例值 |
$uri |
當前 URI(不含參數) |
/api/users |
$request_uri |
原始請求 URI(含參數) |
/api/users?page=1 |
$args |
查詢參數 |
page=1&size=10 |
$arg_name |
特定參數值 |
$arg_page → 1 |
$request_method |
請求方法 |
GET, POST |
$host |
請求的 Host |
example.com |
$http_host |
Host 標頭(含 port) |
example.com:8080 |
$scheme |
協定 |
http, https |
| 變數 |
說明 |
範例值 |
$remote_addr |
客戶端 IP |
192.168.1.100 |
$remote_port |
客戶端 port |
52431 |
$http_user_agent |
User-Agent |
Mozilla/5.0... |
$http_referer |
Referer 標頭 |
https://google.com |
$http_cookie |
Cookie 標頭 |
session=abc123 |
$http_x_forwarded_for |
X-Forwarded-For |
10.0.0.1, 192.168.1.1 |
| 變數 |
說明 |
範例值 |
$server_name |
匹配的 server_name |
example.com |
$server_addr |
伺服器 IP |
192.168.1.1 |
$server_port |
伺服器 port |
80, 443 |
$document_root |
root 目錄路徑 |
/var/www/html |
$request_filename |
完整檔案路徑 |
/var/www/html/index.html |
| 變數 |
說明 |
範例值 |
$status |
回應狀態碼 |
200, 404 |
$body_bytes_sent |
傳送的位元組數 |
1024 |
$request_time |
請求處理時間(秒) |
0.032 |
log_format detailed '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'rt=$request_time';
if ($request_method = POST) {
}
add_header X-Request-ID $request_id;
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;
rewrite ^/old/(.*)$ /new/$1 permanent;
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff|woff2)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
location ~ /\. {
deny all;
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
}
upstream backend {
least_conn;
server 192.168.1.101:3000 weight=3;
server 192.168.1.102:3000 weight=2;
server 192.168.1.103:3000 backup;
}
server {
listen 80;
server_name api.example.com;
location /api/ {
proxy_pass http://backend;
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_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
}
location /ws/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_read_timeout 86400;
}
}
server {
listen 80;
server_name app.example.com;
root /var/www/frontend/dist;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
location /api/ {
proxy_pass http://localhost: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;
}
location /static/ {
alias /var/www/frontend/dist/static/;
expires 1y;
add_header Cache-Control "public, immutable";
}
}
server {
listen 80;
server_name example.com www.example.com;
root /var/www/main;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
server {
listen 80;
server_name blog.example.com;
root /var/www/blog;
index index.php index.html;
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
server {
listen 80;
server_name admin.example.com;
allow 10.0.0.0/8;
allow 192.168.1.0/24;
deny all;
root /var/www/admin;
index index.html;
location / {
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.htpasswd;
try_files $uri $uri/ =404;
}
location ~* \.(env|git|log)$ {
deny all;
return 404;
}
}
location / {
}
location /api/ {
}
location ^~ /static/ {
}
location ~* \.(css|js)$ {
}
location ^~ /static/ {
location ~* \.(css|js)$ {
expires 30d;
}
}
location /images/ {
alias /var/www/static;
}
location /images/ {
alias /var/www/static/;
}
location / {
try_files $uri $uri/ =404;
}
location / {
try_files $uri $uri/ /index.html;
}
location /admin/ {
deny all;
allow 192.168.1.0/24;
}
location /admin/ {
allow 192.168.1.0/24;
deny all;
}
sudo nginx -t
sudo nginx -s reload
sudo tail -f /var/log/nginx/error.log
| 優先順序 |
修飾符 |
說明 |
範例 |
| 1 |
= |
精確匹配 |
location = / |
| 2 |
^~ |
前綴優先 |
location ^~ /static/ |
| 3 |
~ |
正則(大小寫敏感) |
location ~ \.php$ |
| 3 |
~* |
正則(不分大小寫) |
location ~* \.(jpg|png)$ |
| 4 |
(無) |
前綴匹配 |
location /api/ |
| 指令 |
用途 |
範例 |
listen |
監聽 port |
listen 80; |
server_name |
域名 |
server_name example.com; |
root |
文件根目錄 |
root /var/www; |
alias |
路徑替換 |
alias /var/www/static/; |
index |
預設檔案 |
index index.html; |
try_files |
依序嘗試 |
try_files $uri $uri/ =404; |
proxy_pass |
反向代理 |
proxy_pass http://backend; |
allow/deny |
IP 控制 |
allow 192.168.1.0/24; |
auth_basic |
密碼認證 |
auth_basic "Protected"; |
建立日期:2025-12-03
標籤:#Nginx #Web伺服器 #配置 #反向代理 #location