How to return HTTP Code if OPTIONS preflight

1. Caddy version (caddy version):

caddy 2.2.1

2. How I run Caddy:

Systemctl start caddy

a. System environment:

ubuntu 20.04

b. Command:

Paste command here.

c. Service/unit/compose file:

Paste full file contents here.
Make sure backticks stay on their own lines,
and the post looks nice in the preview pane.

d. My complete Caddyfile or JSON config:

:2020 {
         @options {
            method OPTIONS
        respond @options 204
        handle {

               header Access-Control-Allow-Origin *
                header Access-Control-Allow-Credentials true
                header Access-Control-Allow-Headers Auth-Token,Content-Type,Access-Token
               header  Access-Control-Allow-Methods OPTIONS,GET,POST
                encode zstd gzip


3. The problem I’m having:

I want use header Access-Control-Allow-Origin * to allow CROS, but GOT 405 ERROR in my browser.

This is the detailed message of the error:

A cross-origin resource sharing (CORS) request was blocked because the response to the associated preflight request had an unsuccessful HTTP status code and/or was a redirect.

To fix this issue, ensure all CORS preflight `OPTION` requests are answered with a successful HTTP status code (2xx) and do not redirect.

4. Error messages and/or full log output:

5. What I already tried:

When use nginx, this can be done by add this code :

if ($request_method = 'OPTIONS') {
           return 204;

So, I want to know if caddy can support this?

6. Links to relevant resources:

Please upgrade to v2.4.6!

Your config has messy syntax, so it’s hard to read. You’re meant to paste your config in the spot where it says “Paste config here”, which is between the ``` triple backticks, which make the post use code formatting.

I think your issue is that handle has a higher directive order than respond, so it gets sorted to be executed after the rest:

You can use a handle @options block and put respond inside of that, and it should fix it.

But the way OPTIONS is typically used, browsers expect to receive the CORS headers in the OPTIONS request as well, so you probably need to move the header lines outside of the handle blocks so they apply to all requests (including OPTIONS).


This topic was automatically closed after 30 days. New replies are no longer allowed.