opyebCorsLab

各伺服器 CORS 設定:Workers、Nginx、Express、Apache 比較

伺服器設定 · 10 分鐘

一句話: 同一份允許清單在四個平台安全實作的方法、各自隱藏的陷阱,以及上線前檢查清單。

CORS 是回應標頭的問題,不是應用程式的問題。因此在邊緣(Workers)、反向代理(Nginx)、應用程式(Express)、網頁伺服器(Apache)都能用同樣四個原則設定。

  1. 只回傳允許清單內的 Origin。
  2. 只列出實際使用的方法與標頭。
  3. OPTIONS 以 2xx 快速回應。
  4. 每個回應都加上 Vary: Origin。

1. Cloudflare Workers

const ALLOWED = new Set(["https://app.example.com"]);
export default {
  async fetch(request) {
    const origin = request.headers.get("Origin") || "";
    const h = new Headers({ "Vary": "Origin" });
    if (ALLOWED.has(origin)) {
      h.set("Access-Control-Allow-Origin", origin);
      h.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
      h.set("Access-Control-Allow-Headers", "content-type, authorization");
      h.set("Access-Control-Max-Age", "600");
    }
    if (request.method === "OPTIONS") return new Response(null, { status: 204, headers: h });
    return new Response(JSON.stringify({ ok: true }), { headers: h });
  }
};

邊緣常自動快取,Vary 特別重要;需要驗證的路徑也請檢視 Cache-Control: private。

2. Nginx

map $http_origin $cors_origin {
    default "";
    "https://app.example.com" $http_origin;
}

location /api/ {
    add_header Vary "Origin" always;
    add_header Access-Control-Allow-Origin $cors_origin always;
    add_header Access-Control-Allow-Methods "GET, POST, OPTIONS" always;
    add_header Access-Control-Allow-Headers "content-type, authorization" always;
    if ($request_method = OPTIONS) {
        add_header Access-Control-Allow-Origin $cors_origin always;
        add_header Access-Control-Allow-Methods "GET, POST, OPTIONS" always;
        add_header Access-Control-Allow-Headers "content-type, authorization" always;
        add_header Content-Length 0;
        add_header Content-Type text/plain;
        return 204;
    }
}

兩個陷阱:map 對未列出的 Origin 回傳空字串,瀏覽器會忽略空值標頭(這是預期行為);if 內只放 add_header 與 return 才安全。另外,子區塊一旦使用 add_header,就不會繼承父區塊的 add_header。

3. Express

const ALLOWED = new Set(["https://app.example.com"]);
app.use(cors({
  origin(origin, callback) {
    if (!origin) return callback(null, false);
    return callback(null, ALLOWED.has(origin));
  },
  methods: ["GET", "POST", "OPTIONS"],
  allowedHeaders: ["content-type", "authorization"],
  credentials: true,
  maxAge: 600,
  optionsSuccessStatus: 204
}));

origin 傳入函式時,cors 會自動加上 Vary: Origin;若自行設定標頭,別忘了 res.vary("Origin")。

4. Apache

<IfModule mod_headers.c>
  SetEnvIf Origin "^https://app\.example\.com$" CORS_OK=1
  Header always set Vary "Origin" env=CORS_OK
  Header always set Access-Control-Allow-Origin "%{Origin}e" env=CORS_OK
  Header always set Access-Control-Allow-Methods "GET, POST, OPTIONS" env=CORS_OK
  Header always set Access-Control-Allow-Headers "content-type, authorization" env=CORS_OK
</IfModule>
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{REQUEST_METHOD} ^OPTIONS$
  RewriteRule ^(.*)$ $1 [R=200,L]
</IfModule>

SetEnvIf 的正規式要用 ^ 與 $ 對整個 Origin 比對。Header always set 也會套用到錯誤回應,可減少 4xx 時 CORS 標頭消失的問題。

5. 上線前檢查清單

  • 允許清單沒有殘留開發或測試網域。
  • credentials: true 的地方沒有 *。
  • 預檢回應為 2xx,Allow-Headers 涵蓋所有實際送出的標頭。
  • 包含錯誤回應在內,每個回應都有 Vary: Origin。
  • CDN 快取規則不會移除或覆寫 CORS 標頭。

6. 在 CorsLab

在③產生器輸入允許 Origin、方法、標頭、Max-Age,會得到五種程式碼(Workers、Nginx、兩種 Express、Apache)。按「套用到模擬器」即可用相同數值立即確認判定。

把同樣的請求與回應放進模擬器,就能立刻看到是否通過以及該改哪個標頭。

開啟 CorsLab

常見問題

在代理處理 CORS 還是在應用程式處理比較好?

只在一個地方處理。兩邊都設定容易產生重複標頭與「multiple values」錯誤。

為什麼 Nginx 的 add_header 會消失?

子區塊使用 add_header 後就不再繼承父層的 add_header。把需要的標頭都寫在同一個區塊。

CDN 後面還有 Nginx 時該在哪設定?

在邊緣處理、原伺服器不動最單純;兩邊同時設定容易出現重複標頭。

來源

繼續閱讀

輸入資料傳送至伺服器 0 筆(廣告與聯盟小工具除外)