使用 curl -I 獲取頭資訊時遇到 HTTP 302 重導向,提取 Location 欄位的新 URL 再次請求卻回傳 HTTP 400 Bad Request,但手動複製該 URL 請求卻正常(200 OK)。
透過 hexdump 比對發現:
0A(LF 換行符)0D 0A(CRLF)或無控制字元LF 導致 HTTP 請求行格式錯誤,伺服器回傳 400URL=$(cat log | grep '^Location' | cut -f2 -d ' ')
curl -s -I "$URL" > log # 含換行符,請求失敗
URL=$(cat log | grep '^Location' | cut -f2 -d ' ' | sed 's/\r//; s/\n//')
curl -s -I "$URL" > log
URL=$(cat log | grep '^Location' | cut -f2 -d ' ' | tr -d '\r\n')
curl -s -I "$URL" > log
curl -s -L -I "原始URL" > log
# -L 參數自動追蹤 3xx 重導向,無需手動解析 Location
-L 參數 讓 curl 自動處理重導向鏈\r、\n、\r\n)printf '%s' "$URL" 而非 echo 輸出變數,避免殘留換行set -euo pipefail 並驗證 URL 格式| 參數 | 說明 |
|---|---|
-L | 跟隨重導向(預設最多 50 次) |
--max-redirs N | 設定最大重導向次數 |
--post301/--post302/--post303 | 重導向時保持 POST 方法不轉為 GET |
-H "Referer: ..." | 攜帶 Referer 頭,某些防盜鏈需求 |
理解 HTTP 協議細節與 Shell 變數處理特性,能避開此類「看似玄學實則細節」的坑。