萬盛學電腦網

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

Nginx 301/302 重定向跳轉配置詳解:rewrite 指令、flag 標記與 if 條件實戰

Nginx 重定向核心在於 rewrite 指令搭配 permanent (301) 或 redirect (302) 標記。本文系統整理完整配置範例、四大 Flag 差異、if 條件判斷、防盜鏈實戰與 URL 重寫 vs 跳轉的本質區別。

一、最簡單的 301/302 整站跳轉

301 永久重定向 (SEO 權重傳遞)


server {
    listen 80;
    server_name downcc.com;
    rewrite ^/(.*) https://www.downcc.com/$1 permanent;
    access_log off;
}

302 臨時重定向 (不傳遞權重)


server {
    listen 80;
    server_name downcc.com;
    rewrite ^/(.*) https://www.downcc.com/$1 redirect;
    access_log off;
}

二、rewrite 指令語法與四大 Flag 核心差異


rewrite 正則表達式 替換目標 [flag];
Flag行為瀏覽器網址列適用場景
last重寫後**重新搜尋** location 匹配 (內部跳轉)不變URL 重寫、偽靜態、反向代理前置處理
break重寫後**停止**匹配,直接使用當前 location不變在 location 內完成重寫,不再進入其他 location
redirect返回 302 臨時重定向變更 為目標 URL臨時維護、A/B 測試、舊域名暫時導流
permanent返回 301 永久重定向變更 為目標 URL域名遷移、HTTPS 強制、SEO 權重轉移

核心口訣: last/break = 伺服器端內部重寫 (網址列不變);redirect/permanent = 瀏覽器端跳轉 (網址列變化)。

三、實戰範例:目錄下檔案重寫至新路徑 (last/break)


location /download/ {
    # 將 /download/xxx/m/yyy.* 重寫為 /download/xxx/nginx-rewrite/yyy.gz
    # $1 對應第一個 (),即 /download/xxx
    # $2 對應第二個 (),即 yyy
    rewrite ^(/download/.*)/m/(.*)..*$ $1/nginx-rewrite/$2.gz break;
}

四、if 條件判斷與進階重定向

if 僅能在 server 與 location 區塊中使用。

1. User-Agent 判斷 (舊版 IE 導向專用目錄)


if ($http_user_agent ~ MSIE) {
    rewrite ^(.*)$ /nginx-ie/$1 break;
}
  • ~ 大小寫敏感匹配;~* 不區分大小寫;!~/!~* 為不匹配。

2. 檔案/目錄存在性判斷 (前端控制器模式)


if (!-e $request_filename) {
    proxy_pass https://127.0.0.1:8080;  # 轉發給後端應用
    # 或 rewrite ^/(.*)$ /index.php/$1 last; (PHP 框架常用)
}
  • -f 檔案存在、-d 目錄存在、-e 檔案或目錄存在、-x 可執行。

3. 防盜鏈實戰 (return 直接回傳狀態碼)


location ~* \.(gif|jpg|png|swf|flv)$ {
    valid_referers none blocked www.downcc.com www.test1.com;
    if ($invalid_referer) {
        return 404;  # 或 return 403; rewrite ^/ https://example.com/forbidden.png redirect;
    }
}

五、常見誤區與避坑指南

  • rewrite 死循環: 在同一 location 內使用 last 導致反覆匹配同一規則 → 改用 break 或調整正則避免自匹配。
  • proxy_pass 帶 URI 截斷: proxy_pass https://backend/; (尾隨斜線) 會截掉匹配前綴;無斜線則透傳完整路徑。
  • 301 快取陷阱: 瀏覽器會強力快取 301,測試時用 curl -I 或無痕模式,生產上線前確認無誤。
  • 正則效能: 複雜正則在高併發下消耗 CPU,簡單前綴匹配優先用 location /prefix/。

一句話總結: 內部重寫用 last/break,外部跳轉用 redirect/permanent;if 能不用盡量不用 (Nginx 作者建議用 location 匹配替代),防盜鏈用 valid_referers + return 最乾淨。

copyright © 萬盛學電腦網 all rights reserved