Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx set proxy_set_header if header is present

I'm using AWS CloudFront to terminate my SSL before hitting my backend, and need to distinguish this traffic from non-CloudFront traffic to set a proxy_set_header in Nginx.

I believe the best way to do this would be to check for the X-Amz-Cf-Id header (added by CloudFront), and set the proxy_set_header when it's present. However, I'm aware it's not possible to set proxy_set_header in an Nginx if statement, which leads to my question.

How can I set a proxy_set_header value only when that header is present?

like image 686
Manonthemoon Avatar asked Dec 02 '16 13:12

Manonthemoon


1 Answers

if statements aren't a good way of setting custom headers because they may cause statements outside the if block to be ignored.

You can use a map directive instead which is not prone to the same problems.

# outside server blocks
map $http_X_Amz_Cf_Id $is_cloudfront {
    default "No";
    ~. "Yes";  # Regular expression to match any value
}

Then:

# inside location block
proxy_set_header X_Custom_Header $is_cloudfront;
like image 86
Ian Mackinnon Avatar answered Nov 04 '22 21:11

Ian Mackinnon