在 Nginx 中停用 HTTP OPTIONS 方法(預檢請求)的驗證

在 Nginx 中停用 HTTP OPTIONS 方法(預檢請求)的驗證

我的問題與此處描述的問題完全相同:停用 HTTP OPTIONS 方法的身份驗證(預檢請求)。我正在嘗試同時使用 CORS 和 HTTP 密碼。當瀏覽器看到退回的 OPTIONS(狀態代碼 401)時,由於某種原因,它會立即檢查 CORS 標頭(該標頭將不存在)並拒絕請求。

這是我的配置:

location /api/ {
    proxy_pass http://127.0.0.1:14000;
    proxy_set_header Host $host;
    add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
    add_header Access-Control-Allow-Origin $http_origin;
    add_header Access-Control-Allow-Headers "Authorization, Content-Type";
    add_header Access-Control-Allow-Credentials true;
    auth_basic            "Restricted Area";
    auth_basic_user_file  /var/www/admin.htpasswd;
}

答案1

這是我想出來的解決方案。不過,它解決了重複所有 CORS add_header 指令的問題。

location /api/ {
    proxy_pass http://127.0.0.1:14000;
    proxy_set_header Host $host;
    add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
    add_header Access-Control-Allow-Origin $http_origin;
    add_header Access-Control-Allow-Headers "Authorization, Content-Type";
    add_header Access-Control-Allow-Credentials true;
    if ($request_method = OPTIONS) {
        add_header Content-Length 0;
        add_header Content-Type text/plain;
        add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
        add_header Access-Control-Allow-Origin $http_origin;
        add_header Access-Control-Allow-Headers "Authorization, Content-Type";
        add_header Access-Control-Allow-Credentials true;
        return 200;
    }
    auth_basic            "Restricted Area";
    auth_basic_user_file  /var/www/admin.htpasswd;
}

答案2

我找到了一個更乾淨的解決方案,可以讓節點管理請求:

將以下配置放入“location”中,並從伺服器中刪除任何 auth_basic。這會起作用。

  location / {
    # Your node proxy configuration for example #

    # Make options requests work #
    limit_except OPTIONS {
      auth_basic "Restricted access zone";
      auth_basic_user_file /etc/nginx/pass/protected;
    }
  }

答案3

以下資訊位於limit_ except/if 區塊問題,我建議使用map

map $request_method $auth_basic_value {
    default "Restricted";
    "OPTIONS" "off";
}


location / {
        auth_basic $auth_basic_value;
}

請記住,如果您try_files在該位置有一些,可能會將查詢重寫到另一個位置,那麼您可能還需要設定auth_basic $auth_basic_value.

相關內容