Rewrite 核心匹配與判斷語法
正則修飾符
~:區分大小寫匹配
~*:不區分大小寫匹配
!~ / !~*:不匹配 (區分/不區分大小寫)
檔案/目錄存在性判斷
-f / !-f:檔案存在/不存在
-d / !-d:目錄存在/不存在
-e / !-e:檔案或目錄存在/不存在
-x / !-x:可執行/不可執行
旗標
last:完成重寫,發起新內部請求 (最常用)
break:終止匹配,不再處理後續規則
redirect:302 臨時重導向,瀏覽器網址列變更
permanent:301 永久重導向,瀏覽器網址列變更
常用全域變數 (可用於 if 條件與重寫目標)
$args $query_string # 查詢字串
$content_length $content_type
$document_root $document_uri
$host $http_user_agent $http_cookie $http_referer
$limit_rate $request_method $remote_addr $remote_port $remote_user
$request_filename $request_uri $request_body_file
$scheme $server_protocol $server_addr $server_name $server_port
$uri
實戰範例集
1. 框架路由 (QeePHP 風格)
if (!-d $request_filename) {
rewrite ^/([a-zA-Z]+)/([a-zA-Z]+)/?(.*)$ /index.php?namespace=user&controller=$1&action=$2&$3 last;
rewrite ^/([a-zA-Z]+)/?$ /index.php?namespace=user&controller=$1 last;
break;
}
2. 子網域轉參數
# abc.domain.com/sort/2 → /index.php?act=sort&cid=abc&id=2
if ($host ~* (.*)\.domain\.com) {
set $sub_name $1;
rewrite ^/sort\/(\d+)\/?$ /index.php?act=sort&cid=$sub_name&id=$1 last;
}
3. 目錄對調
# /123456/xxxx → /xxxx?id=123456
rewrite ^/(\d+)/(.+)/ /$2?id=$1 last;
4. User-Agent 導向特定目錄 (IE 範例)
if ($http_user_agent ~ MSIE) {
rewrite ^(.*)$ /nginx-ie/$1 break;
}
5. 目錄自動補齊斜線 (永久重導向)
if (-d $request_filename) {
rewrite ^/(.*)([^/])$ https://$host/$1$2/ permanent;
}
6. 禁止 .htaccess 存取
location ~/\.ht { deny all; }
7. 禁止多個敏感目錄
location ~ ^/(cron|templates)/ { deny all; break; }
8. 禁止 /data 開頭所有路徑 (遞迴)
location ~ ^/data { deny all; }
9. 禁止單一目錄 (非遞迴)
location /searchword/cron/ { deny all; }