Nginx sets proxy_set_header if header is present

I use AWS CloudFront to interrupt my SSL before hitting my backend, and you need to distinguish this traffic from non-CloudFront traffic in order to set proxy_set_header in Nginx.

I believe the best way to do this is to check the X-Amz-Cf-Id header ( added by CloudFront ) and set proxy_set_header if any. However, I know that it is not possible to set proxy_set_header in a Nginx if statement, which leads to my question.

How to set the value of proxy_set_header only if this header is present?

+5
source share
2 answers

General answer: you can set the variables in if and then use the variable. Like this:

 set $variable ""; if ($http_X_Amz_Cf_Id) { set $variable "somevalue"; } proxy_set_header someheader $variable; 
+2
source
Operators

if are not a good way to set custom headers, because they can cause statements outside the if block to be ignored .

Instead, you can use the map directive , which is not subject 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; 
+4
source

Source: https://habr.com/ru/post/1260708/


All Articles