Skip to content

Instantly share code, notes, and snippets.

@dfang
Created December 31, 2023 11:47
Show Gist options
  • Save dfang/3272ff8dd4cbf0309bf7350c08b5a316 to your computer and use it in GitHub Desktop.
Save dfang/3272ff8dd4cbf0309bf7350c08b5a316 to your computer and use it in GitHub Desktop.
setup caddy 2 cors
(cors) {
        @cors_preflight{args.0} method OPTIONS
        @cors{args.0} header Origin {args.0}
        # @cors{args.0} header Origin "{args.0} Vary Origin"
        # You should always append Vary: Origin header when you want to use multiple URLs, see: fetch.spec.whatwg.org/#cors-protoc ol-and-http-caches
        handle @cors_preflight{args.0} {
                header {
                        Access-Control-Allow-Origin "{args.0}"
                        Access-Control-Allow-Methods "GET, POST, PUT, PATCH, DELETE, OPTIONS"
                        # Access-Control-Allow-Headers *
                        Access-Control-Allow-Headers "Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, Content-Type , Access-Control-Request-Method, Access-Control-Request-Headers, x-client-info, authorization, x-upsert, cache-control, apikey"
                        Access-Control-Allow-Credentials "true"
                        Access-Control-Max-Age "3600"
                        defer
                }
                respond "" 204
        }
        handle @cors{args.0} {
                header {
                        Access-Control-Allow-Origin "{args.0}"
                        Access-Control-Expose-Headers *
                        # Access-Control-Allow-Headers *
                        Access-Control-Allow-Headers "Authorization"
                        Access-Control-Allow-Credentials "true"
                        defer
               }
        }
}


(cors) {
        @cors_preflight{args.0} method OPTIONS
        @cors{args.0} header Origin {args.0}

        handle @cors_preflight{args.0} {
                header {
                        Access-Control-Allow-Origin "{args.0}"
                        Access-Control-Allow-Methods "GET, POST, PUT, PATCH, DELETE, OPTIONS"
                        Access-Control-Allow-Headers *
                        Access-Control-Max-Age "3600"
                        defer   #turn on defer on your header directive to make sure the new header values are set after proxying
                }
                respond "" 204
        }

        handle @cors{args.0} {
                header {
                        Access-Control-Allow-Origin "{args.0}"
                        Access-Control-Expose-Headers *
                        defer
                }
        }
}

mysite.com {
    import cors https://api.mysite.com
    import cors http://localhost:8080
    reverse_proxy http://localhost:12345
}

@dfang
Copy link
Author

dfang commented Dec 31, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment