Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx: Reject request if header is not present or wrong

Tags:

nginx

If I have the headers: X_HEADER1 & X_HEADER2, I want to reject all requests if either of these headers are not set or do not contain the correct values. What is the best way to do this?

Thanks

like image 824
Paul Avatar asked Sep 23 '13 23:09

Paul


People also ask

Does nginx pass headers?

By default, NGINX redefines two header fields in proxied requests, “Host” and “Connection”, and eliminates the header fields whose values are empty strings. “Host” is set to the $proxy_host variable, and “Connection” is set to close . In this configuration the “Host” field is set to the $host variable.

What is Add_header in nginx?

The Nginx add_header directive allows you to define an arbitrary response header and value to be included in all response codes, which are equal to 200 , 201 , 204 , 206 , 301 , 302 , 303 , 304 , or 307 . This can be defined from within your nginx.

Where do I put headers in nginx?

Note: If you want to apply these headers to specific files, please add the add_header line in location block(Nginx) or Header set line in filesMatch block(Apache).


2 Answers

You can use two IF statements either before or in the location block to inspect the headers and then return a 403 error code if it is present. Alternatively, you can use those IF statements to rewrite to a specific location block and deny all in that location:

if ($http_x_custom_header) {     return 403; } 

Reference:
https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/
https://nginx.org/en/docs/http/ngx_http_access_module.html

Adding more detail per comment/request:

if ($http_x_custom_header) {     return 405; } 

this looks to see if header exists

if you want to check to see if the correct values exist, then you first need to map the correct values to a variable.

map $http_x_header $is_ok {     default "0";     Value1  "1";     Value2  "1";     Value3  "1"; }  if ($is_ok) {     return 405;  } 

this first maps the header value to whether or not its ok, then checks to see if the variable is ok.

EDIT: Removed semicolon after map block since this causes an error.

like image 124
Rami Avatar answered Oct 19 '22 12:10

Rami


I researched a lot to solve a simple problem: Only allow proxy_pass if request have a specific token in the header. I tried all the answers here and nothing worked how I liked. My final solution is:

location /api {     proxy_http_version 1.1;      if ($http_authorization != "Bearer 1234") {         return 401;     }      proxy_pass http://app:3000/; } 

References:

NGINX not equal to

nginx - read custom header from upstream server

https://serverfault.com/questions/490760/nginx-location-exact-match-matches-beyond-arguement

https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/

like image 38
Ângelo Polotto Avatar answered Oct 19 '22 11:10

Ângelo Polotto