Nginx 重定向核心在於 rewrite 指令搭配 permanent (301) 或 redirect (302) 標記。本文系統整理完整配置範例、四大 Flag 差異、if 條件判斷、防盜鏈實戰與 URL 重寫 vs 跳轉的本質區別。
server {
listen 80;
server_name downcc.com;
rewrite ^/(.*) https://www.downcc.com/$1 permanent;
access_log off;
}
server {
listen 80;
server_name downcc.com;
rewrite ^/(.*) https://www.downcc.com/$1 redirect;
access_log off;
}
rewrite 正則表達式 替換目標 [flag];
| Flag | 行為 | 瀏覽器網址列 | 適用場景 |
|---|---|---|---|
last | 重寫後**重新搜尋** location 匹配 (內部跳轉) | 不變 | URL 重寫、偽靜態、反向代理前置處理 |
break | 重寫後**停止**匹配,直接使用當前 location | 不變 | 在 location 內完成重寫,不再進入其他 location |
redirect | 返回 302 臨時重定向 | 變更 為目標 URL | 臨時維護、A/B 測試、舊域名暫時導流 |
permanent | 返回 301 永久重定向 | 變更 為目標 URL | 域名遷移、HTTPS 強制、SEO 權重轉移 |
核心口訣: last/break = 伺服器端內部重寫 (網址列不變);redirect/permanent = 瀏覽器端跳轉 (網址列變化)。
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 僅能在 server 與 location 區塊中使用。
if ($http_user_agent ~ MSIE) {
rewrite ^(.*)$ /nginx-ie/$1 break;
}
~ 大小寫敏感匹配;~* 不區分大小寫;!~/!~* 為不匹配。
if (!-e $request_filename) {
proxy_pass https://127.0.0.1:8080; # 轉發給後端應用
# 或 rewrite ^/(.*)$ /index.php/$1 last; (PHP 框架常用)
}
-f 檔案存在、-d 目錄存在、-e 檔案或目錄存在、-x 可執行。
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;
}
}
last 導致反覆匹配同一規則 → 改用 break 或調整正則避免自匹配。proxy_pass https://backend/; (尾隨斜線) 會截掉匹配前綴;無斜線則透傳完整路徑。curl -I 或無痕模式,生產上線前確認無誤。location /prefix/。一句話總結: 內部重寫用
last/break,外部跳轉用redirect/permanent;if能不用盡量不用 (Nginx 作者建議用location匹配替代),防盜鏈用valid_referers+return最乾淨。