nginxcorswebdavpropfind

Nginx WebDAV module ignoring CORS headers


I am running WebDAV using Nginx. I have a JS app using it as a storage. The problem is that the WebDAV extension is removing headers that I added using "add_header" in my config.

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";
    }
  }
}

And when I open a WebDAV connection from my App it requests OPTIONS followed by PROPFIND. The request OPTIONS passes by having correct CORS headers but PROPFIND fails because no CORS headers were set. Note the special case for OPTIONS in the config where I force Nginx to return Http200. Then the headers appear. But when letting the WebDAV to finish then all CORS headers disappear.

Did anyone circumvent this behaviour?


Solution

  • I had the same issue.

    Try adding the always keyword to the add_header statements:

    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 docs:

    Syntax: add_header name value [always];

    Adds the specified field to a response header provided that the response code equals 200, 201 (1.3.10), 204, 206, 301, 302, 303, 304, 307 (1.1.16, 1.0.13), or 308 (1.13.0). [...] If the always parameter is specified (1.7.5), the header field will be added regardless of the response code.

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