| 上下文常量 | 配置文件位置 |
|---|---|
| NGX_HTTP_SRV_CONF | server { ... } 任意位置 |
| NGX_HTTP_SIF_CONF | server { if (...) { ... } } |
| NGX_HTTP_LOC_CONF | location /path { ... } 任意位置 |
| NGX_HTTP_LIF_CONF | location /path { if (...) { ... } } |
syntax: rewrite regex replacement [flag];
context: server, location, if
regex:PCRE 正則,捕獲組可用 $1-$9 反向引用。replacement:替換字串,可包含變量。flag:last | break | redirect | permanent。| Flag | 行為 | 瀏覽器地址欄 | 典型場景 |
|---|---|---|---|
last | 完成本條重寫,重新發起內部子請求,重新匹配 location | 不變 | 根 location /、server 級、需再次匹配其他 location |
break | 完成本條重寫,停止後續 rewrite,直接進入當前 location 後續處理 | 不變 | 非根 location /foo/、配合 proxy_pass |
redirect | 返回 302 臨時重定向 | 變為新 URL | 舊域名遷移、暫時維護頁 |
permanent | 返回 301 永久重定向 | 變為新 URL | SEO 權重傳遞、HTTPS 強制跳轉 |
關鍵區別: last 會觸發 新一輪 location 匹配,break 則停留在當前 location。搭配 alias 用 last,搭配 proxy_pass 用 break。
return code [text];
return code URL;
context: server, location, if
直接返回狀態碼,結束處理。例:
location ~* \.(sh|bash)$ {
return 403;
}
0 開頭字串為假。=、!=。~ (區分大小寫)、~* (不區分)、!~、!~*。-f、!-f、-d、-e、-x。map 或 lua。set $varname "hello world";
break:中斷當前 location/if 後續指令。uninitialized_variable_warn on|off:未初始化變量是否警告,預設 on。$args $query_string # 請求參數
$content_length $content_type # 請求頭
$document_root $document_uri # 路徑
$host $http_host # Host 頭
$http_user_agent $http_cookie # UA / Cookie
$limit_rate $request_method # GET/POST...
$remote_addr $remote_port # 客戶端 IP/埠
$remote_user $request_filename # 物理文件路徑
$request_uri $uri # 原始 URI / 正規化 URI
$query_string $scheme # http/https
$server_protocol $server_addr # 協議/服務器 IP
$server_name $server_port # server_name/埠
location / {
try_files $uri $uri/ /index.php?$query_string;
# 等價於
if (!-e $request_filename) {
rewrite ^/(.*)$ /index.php last;
}
}
rewrite ^/(\d+)/(.+)$ /$2?id=$1 last;
if ($http_user_agent ~ MSIE) {
rewrite ^(.*)$ /ie$1 break;
}
location ~ ^/(cron|templates)/ { deny all; }
location ~ ^/data { deny all; }
location ~* \.(sh|flv|mp3)$ { return 403; }
location ~* \.(gif|jpg|jpeg|png|bmp|webp|ico|svg)$ {
expires 30d; add_header Cache-Control "public";
}
location ~* \.(js|css)$ {
expires 7d; add_header Cache-Control "public";
}
location = /favicon.ico { expires 99d; log_not_found off; access_log off; }
location = /robots.txt { expires 7d; log_not_found off; access_log off; }
server {
listen 80;
server_name www.example.com example.com;
return 301 https://example.com$request_uri;
}
server {
listen 443 ssl http2;
server_name example.com;
# ssl 證書配置...
}
預設重寫會自動保留查詢字串。若需丟棄,在 replacement 末尾加 ?:
rewrite ^/test(.*)$ https://example.com/home? permanent;
rewrite_log on; 在 error_log 記錄重寫過程 (需 error_log /path/log notice;)。curl -v 觀察 301/302 Location 頭。掌握 last/break 語義差異、善用 try_files 替代簡單 rewrite、配合 map 處理複雜映射,是編寫高性能可維護 Nginx 配置的關鍵。