How to add a response header on nginx when using proxy_pass?

前端 未结 5 1790
太阳男子
太阳男子 2020-12-07 11:19

I want to add a custom header for the response received from the server behind nginx.

While add_header works for nginx-processed responses, it does noth

5条回答
  •  天涯浪人
    2020-12-07 12:02

    Hide response header and then add a new custom header value

    Adding a header with add_header works fine with proxy pass, but if there is an existing header value in the response it will stack the values.

    If you want to set or replace a header value (for example replace the Access-Control-Allow-Origin header to match your client for allowing cross origin resource sharing) then you can do as follows:

    # 1. hide the Access-Control-Allow-Origin from the server response
    proxy_hide_header Access-Control-Allow-Origin;
    # 2. add a new custom header that allows all * origins instead
    add_header Access-Control-Allow-Origin *;
    

    So proxy_hide_header combined with add_header gives you the power to set/replace response header values.

    Similar answer can be found here on ServerFault

    UPDATE:

    Note: proxy_set_header is for setting request headers before the request is sent further, not for setting response headers (these configuration attributes for headers can be a bit confusing).

提交回复
热议问题