How to send a response with HAProxy without passing the request to web servers

前端 未结 2 1420
醉梦人生
醉梦人生 2021-02-04 08:27

The server is receiving thousands of OPTIONS requests due to CORS (Cross-Origin Resource Sharing). Right now, every options request is being sent to on

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-04 08:36

    Good news, HAProxy 2.2 just introduced the "Native Response Generator" feature. It works with the http-request return directive, and can be used for serving static files or text strings, including dynamic parameters. The goal is to avoid the usual hacks with errorfile.

    Taking advantage of another directive introduced in version 2.2 (http-after-response), the OP goal could be achieved with the following:

    backend cors_headers
        # http-response won't work here as the response is generated by HAP
        http-after-response set-header Access-Control-Allow-Origin \
            "%[req.hdr(Origin)]"
        http-after-response set-header Access-Control-Max-Age "31536000"
        http-request return status 200 content-type "text/plain" string ""
    

    The set-header and http-request return can be made conditional with an if clause based on the request headers or origin, depending on your needs (see the doc for examples).

    With this technique the headers and response can use variables:

    http-request return status 200 content-type "text/plain" \
        lf-string "Hello, you are: %[src]"
    

提交回复
热议问题