Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 關於伺服器

Nginx 301/302 重導向與 Rewrite 規則完整教學

編輯:關於伺服器

301 永久重導向 vs 302 暫時重導向

類型狀態碼FlagSEO 影響瀏覽器行為
永久重導向301permanent權重傳遞、索引更新快取重導向、網址列更新
暫時重導向302redirect不傳遞權重、保留原索引不快取、網址列更新

基本配置範例

整站 301 導向 (裸域導 www)

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

單頁 302 導向 (維護頁面)

server {
    listen 80;
    server_name maint.example.com;
    rewrite ^/(.*)$ https://www.example.com/maintenance.html redirect;
    access_log off;
}

Rewrite 指令完整語法

rewrite regex replacement [flag];
  • regex:PCRE 正則運算式
  • replacement:替換目標,可使用 $1-$9 反向引用
  • flag:last | break | redirect | permanent

四大 Flag 行為差異

Flag行為瀏覽器網址列適用場景
last重新發起 location 匹配 (內部重寫)不變URL 重寫、反向代理、偽靜態
break停止 rewrite 處理,繼續當前 location不變目錄重寫、內部路徑調整
redirect返回 302 暫時重導向變更暫時維護、A/B 測試
permanent返回 301 永久重導向變更網域遷移、HTTPS 強制、SEO 權重轉移

進階:條件判斷與 If 區塊

User-Agent 判斷 (舊版 IE 導向相容頁)

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

檔案/目錄存在性判斷 (前端路由支援)

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

防盜鏈實作

location ~* \.(gif|jpg|png|swf|flv)$ {
    valid_referers none blocked *.example.com *.partner.com;
    if ($invalid_referer) {
        return 403;
        # 或重導向佔位圖
        # rewrite ^/ https://$host/logo.png redirect;
    }
}

返回狀態碼 (API 限流/封鎖)

location /api/ {
    limit_req zone=api burst=20 nodelay;
    limit_req_status 429;
    # 自定義錯誤頁
    error_page 429 /429.html;
}

實戰:目錄遷移重寫

# 將 /download/xxx/m/yyy.* 重寫為 /download/xxx/nginx-rewrite/yyy.gz
location /download/ {
    rewrite ^(/download/.*)/m/(.*)\..*$ $1/nginx-rewrite/$2.gz break;
}

避坑提醒

  • last 會觸發新一輪 location 匹配,易造成無限循環,需精心設計
  • 正則中 . 需轉義 \.,否則匹配任意字元
  • if 在 location 中行為詭異,能用 try_files/limit_req/valid_referers 就不用 if
  • 大量 rewrite 規則建議提取至獨立檔案 include rewrites.conf;
Copyright © Windows教程網 All Rights Reserved