首页 > 解决方案 > Nginx WebDAV 模块忽略 CORS 标头

问题描述

我正在使用 Nginx 运行 WebDAV。我有一个 JS 应用程序将其用作存储。问题是 WebDAV 扩展正在删除我在配置中使用“add_header”添加的标头。

server {
  # IP, Certificates, fullpath, autoindex ...
  dav_methods      PUT DELETE MKCOL COPY MOVE;
  dav_ext_methods  PROPFIND OPTIONS;
  dav_access       user:rw group:rw all:rw;

  location / {
    root /srv/http/content;

    # Preflighted requests
    if ($request_method = OPTIONS) {
      add_header "Access-Control-Allow-Origin" *;
      add_header "Access-Control-Allow-Methods" "GET, HEAD, POST, PUT, OPTIONS, MOVE, DELETE, COPY, LOCK, UNLOCK, PROPFIND";
      add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept, DNT, X-CustomHeader, Keep-Alive,User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Range, Range, Depth";
      return 200;
    }

    if ($request_method = (GET|POST|HEAD|DELETE|PROPFIND)) {
      add_header "Access-Control-Allow-Origin" *;
      add_header "Access-Control-Allow-Methods" "GET, HEAD, POST, PUT, OPTIONS, MOVE, DELETE, COPY, LOCK, UNLOCK, PROPFIND";
      add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
    }
  }
}

当我从我的应用程序打开 WebDAV 连接时,它会请求OPTIONS后跟PROPFIND. 请求OPTIONS通过具有正确的 CORS 标头而通过,但PROPFIND由于未设置 CORS 标头而失败。OPTIONS请注意我强制 Nginx 返回的配置中的特殊情况Http200。然后出现标题。但是当让 WebDAV 完成时,所有 CORS 标头都会消失。

有没有人规避这种行为?

标签: nginxcorswebdavpropfind

解决方案


我遇到过同样的问题。

尝试将always关键字添加到add_header语句中:

add_header "Access-Control-Allow-Origin" * always;
add_header "Access-Control-Allow-Methods" "GET, HEAD, POST, PUT, OPTIONS, MOVE, DELETE, COPY, LOCK, UNLOCK, PROPFIND" always;
add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept, DNT, X-CustomHeader, Keep-Alive,User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Range, Range, Depth" always;

add_header 文档:

语法:add_header 名称值 [always];

如果响应代码等于 200、201 (1.3.10)、204、206、301、302、303、304、307 (1.1.16、1.0.13) 或 308 (1.13),则将指定字段添加到响应标头.0)。[...] 如果指定了 always 参数(1.7.5),则无论响应代码如何,都将添加标头字段。

https://nginx.org/en/docs/http/ngx_http_headers_module.html


推荐阅读