萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux curl 處理 HTTP 302 重定向陷阱:換行符導致 400 Bad Request

問題現象

使用 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. 手動複製無換行符則成功

解決方案

方法一:sed 刪除 CR (推薦)

URL=$(grep '^Location:' response.log | cut -d' ' -f2 | sed 's/\r$//')

方法二:tr 刪除所有控制字符

URL=$(grep '^Location:' response.log | cut -d' ' -f2 | tr -d '\r\n')

方法三:參數展開 (純 Bash,無外部進程)

URL=$(grep '^Location:' response.log | cut -d' ' -f2)
URL=${URL%$'\r'}  # 移除尾部 \r

方法四:curl 內建跟隨重定向 (最簡潔)

# 直接跟隨重定向獲取最終內容
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"

curl 重定向相關參數速查

參數作用
-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

最佳實踐

  1. 優先用 curl -L 自動跟隨,避免手動提取 URL
  2. 必須手動提取時,**務必清理 \r\n**
  3. 生產腳本加入 --max-redirs 防止無限循環
  4. 驗證最終 URL 有效性再業務使用
  5. 記錄重定向鏈路便於除錯:curl -v -L ...
copyright © 萬盛學電腦網 all rights reserved