使用 curl 獲取重定向 URL 時,提取 Location 頭直接請求返回 400 Bad Request,但手動複製 URL 再請求卻成功。
Location 頭值末尾包含不可見的 \r (CR, 0x0D) 換行符,導致請求行畸形:
GET /path HTTP/1.1\r
Host: example.com\r
\r\r
# 實際發送包含雙重 CR,服務器解析失敗
# 1. 獲取重定向響應頭
curl -s -I "https://example.com/redirect" > response.log
# 2. 提取 Location (錯誤方式)
URL=$(grep '^Location:' response.log | cut -d' ' -f2)
# 3. 查看隱藏字符
echo "$URL" | od -c
# 輸出: ... M P 4 \r \n
# 4. 直接請求失敗
curl -s -I "$URL"
# HTTP/1.1 400 Bad Request
# 5. 手動複製無換行符則成功
URL=$(grep '^Location:' response.log | cut -d' ' -f2 | sed 's/\r$//')
URL=$(grep '^Location:' response.log | cut -d' ' -f2 | tr -d '\r\n')
URL=$(grep '^Location:' response.log | cut -d' ' -f2)
URL=${URL%$'\r'} # 移除尾部 \r
# 直接跟隨重定向獲取最終內容
curl -L -s -I "https://example.com/redirect"
# 僅獲取最終有效 URL
curl -L -s -o /dev/null -w "%{url_effective}" "https://example.com/redirect"
#!/usr/bin/env bash
# robust_redirect.sh - 健壯處理 HTTP 重定向
follow_redirect() {
local url="$1"
local max_redirects=10
local count=0
while [[ $count -lt $max_redirects ]]; do
# 獲取響應頭
local response
response=$(curl -s -I --max-redirs 0 "$url") || return 1
# 檢查狀態碼
local status
status=$(echo "$response" | head -1 | awk '{print $2}')
case $status in
200)
echo "$url"
return 0
;;
301|302|303|307|308)
# 提取 Location 並清理
local location
location=$(echo "$response" | grep -i '^location:' | head -1 | cut -d' ' -f2- | tr -d '\r\n')
if [[ -z "$location" ]]; then
echo "錯誤: 重定向缺少 Location 頭" >&2
return 1
fi
# 處理相對 URL
if [[ "$location" != http* ]]; then
local base_url
base_url=$(echo "$url" | sed -E 's|(https?://[^/]+).*|\1|')
location="${base_url}${location}"
fi
url="$location"
((count++))
;;
*)
echo "錯誤: 意外狀態碼 $status" >&2
return 1
;;
esac
done
echo "錯誤: 重定向次數超過限制 ($max_redirects)" >&2
return 1
}
# 使用
final_url=$(follow_redirect "https://example.com/redirect")
curl -s -I "$final_url"
| 參數 | 作用 |
|---|---|
-L, --location | 跟隨重定向 (3xx) |
--max-redirs N | 最大重定向次數 (默認 50) |
-I, --head | 僅獲取頭部 |
-w, --write-out | 自定義輸出格式 (如 %{url_effective}) |
--resolve | 指定域名解析,繞過 DNS |
-H, --header | 添加請求頭 |
# 相對路徑重定向
# Location: /new/path
# 需手動拼接基礎 URL
# 協議相對 URL
# Location: //cdn.example.com/file
# 需補全協議
# JavaScript 重定向 (curl 無法處理)
# window.location.href = "..."
# 需用 headless browser (Puppeteer/Playwright)
# Meta Refresh 重定向
#
# curl 無法處理,需解析 HTML
curl -L 自動跟隨,避免手動提取 URL\r\n**--max-redirs 防止無限循環curl -v -L ...