授权标头不与HTTP OPTIONS请求一起发送。我想仅在请求是OPTIONS时禁用此身份验证,并将其保留为其他请求。这是我目前的相关配置代码。似乎无法理解为什么它不起作用。我总是在OPTIONS请求上获得401 Unauthorized Error。
location ~ /foo/bar
{
if ($request_method = OPTIONS) {
set $auth_basic "off";
}
if ($request_method != OPTIONS)
{
set $auth_basic "Resctricted";
set $auth_basic_user_file /var/www/.htpasswd;
}
auth_basic $auth_basic;
auth_basic_user_file $auth_basic_user_file;
}
答案 0 :(得分:3)
看起来它是一个旧帖子,但找到了这个解决方案:
将以下配置放在" 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;
}
}
答案 1 :(得分:1)
处理此问题的最简单方法是允许nginx处理OPTIONS
请求:
server {
listen 80;
server_name example.com;
root /var/www;
auth_basic "Resctricted";
auth_basic_user_file /var/www/.htpasswd;
location / {
if ($request_method = OPTIONS) {
add_header Access-Control-Allow-Origin "http://example.com";
add_header Access-Control-Allow-Methods "GET, OPTIONS";
add_header Access-Control-Allow-Headers "Authorization";
add_header Access-Control-Allow-Credentials "true";
add_header Content-Length 0;
add_header Content-Type text/plain;
return 200;
}
}
}
这将允许OPTIONS
在不需要身份验证的情况下获得响应:
scott@Carl www $ curl -i -X OPTIONS http://example.com
HTTP/1.1 200 OK
Server: nginx
Date: Sat, 17 Jun 2017 00:09:52 GMT
Content-Type: application/octet-stream
Content-Length: 0
Connection: keep-alive
Access-Control-Allow-Origin: http://example.com
Access-Control-Allow-Methods: GET, OPTIONS
Access-Control-Allow-Headers: Authorization
Access-Control-Allow-Credentials: true
Content-Length: 0
Content-Type: text/plain
scott@Carl www $ curl -i http://example.com
HTTP/1.1 401 Unauthorized
Server: nginx
Date: Sat, 17 Jun 2017 00:09:59 GMT
Content-Type: text/html
Content-Length: 188
Connection: keep-alive
WWW-Authenticate: Basic realm="Resctricted"
<html>
<head><title>401 Authorization Required</title></head>
<body bgcolor="white">
<center><h1>401 Authorization Required</h1></center>
<hr><center>nginx</center>
</body>
</html>