萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Nginx Rewrite 重寫規則完整指南:指令、標誌、變量與實戰範例

Rewrite 指令可出現的上下文

上下文常量配置文件位置
NGX_HTTP_SRV_CONFserver { ... } 任意位置
NGX_HTTP_SIF_CONFserver { if (...) { ... } }
NGX_HTTP_LOC_CONFlocation /path { ... } 任意位置
NGX_HTTP_LIF_CONFlocation /path { if (...) { ... } }

核心指令詳解

1. rewrite

syntax: rewrite regex replacement [flag];
context: server, location, if
  • regex:PCRE 正則,捕獲組可用 $1-$9 反向引用。
  • replacement:替換字串,可包含變量。
  • flag:last | break | redirect | permanent。

Flag 差異對比

Flag行為瀏覽器地址欄典型場景
last完成本條重寫,重新發起內部子請求,重新匹配 location不變根 location /、server 級、需再次匹配其他 location
break完成本條重寫,停止後續 rewrite,直接進入當前 location 後續處理不變非根 location /foo/、配合 proxy_pass
redirect返回 302 臨時重定向變為新 URL舊域名遷移、暫時維護頁
permanent返回 301 永久重定向變為新 URLSEO 權重傳遞、HTTPS 強制跳轉

關鍵區別: last 會觸發 新一輪 location 匹配,break 則停留在當前 location。搭配 alias 用 last,搭配 proxy_pass 用 break。

2. return

return code [text];
return code URL;
context: server, location, if

直接返回狀態碼,結束處理。例:

location ~* \.(sh|bash)$ {
    return 403;
}

3. if 條件判斷

  • 變量非空/非 0 為真;空字串、0 開頭字串為假。
  • 比較:=、!=。
  • 正則:~ (區分大小寫)、~* (不區分)、!~、!~*。
  • 文件/目錄存在:-f、!-f、-d、-e、-x。
  • 不支援嵌套、不支援 &&/||,複雜邏輯請用 map 或 lua。

4. set 定義變量

set $varname "hello world";

5. break / uninitialized_variable_warn

  • 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/埠

實戰範例集

1. 前端控制器模式 (ThinkPHP/Laravel/Yii/WordPress)

location / {
    try_files $uri $uri/ /index.php?$query_string;
    # 等價於
    if (!-e $request_filename) {
        rewrite ^/(.*)$ /index.php last;
    }
}

2. 目錄結構換:/id/title → /title?id=id

rewrite ^/(\d+)/(.+)$ /$2?id=$1 last;

3. User-Agent 區分:IE 導向舊版目錄

if ($http_user_agent ~ MSIE) {
    rewrite ^(.*)$ /ie$1 break;
}

4. 封禁敏感目錄/文件

location ~ ^/(cron|templates)/ { deny all; }
location ~ ^/data { deny all; }
location ~* \.(sh|flv|mp3)$ { return 403; }

5. 靜態資源瀏覽器緩存

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; }

6. 強制 HTTPS + 去 www

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 證書配置...
}

7. 參數處理技巧

預設重寫會自動保留查詢字串。若需丟棄,在 replacement 末尾加 ?:

rewrite ^/test(.*)$ https://example.com/home? permanent;

調試技巧

  • rewrite_log on; 在 error_log 記錄重寫過程 (需 error_log /path/log notice;)。
  • curl -v 觀察 301/302 Location 頭。
  • 線上正則測試:regex101.com (選 PCRE)。

掌握 last/break 語義差異、善用 try_files 替代簡單 rewrite、配合 map 處理複雜映射,是編寫高性能可維護 Nginx 配置的關鍵。

copyright © 萬盛學電腦網 all rights reserved