在 Nginx 中禁用 HTTP OPTIONS 方法(预检请求)的身份验证

cle*_*ong 6 nginx cors

我的问题与此处描述的完全相同:Disable authentication for HTTP OPTIONS method (preflight request)。我正在尝试同时使用 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;
}
Run Code Online (Sandbox Code Playgroud)

cle*_*ong 6

这是我想出的解决方案。它解决了复制所有 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;
}
Run Code Online (Sandbox Code Playgroud)