A
A
Andrey2020-07-23 00:53:21
Nginx
Andrey, 2020-07-23 00:53:21

How to add header in NGINX only for specific IP?

I want to display a service header (cache information) only for a user with a specific IP (admin). Here is my configuration:

set $debug_ip_address "8.8.8.8";

location / {
    set $is_debug 1;
    if ($http_x_forwarded_for != $debug_ip_address) {
      set $is_debug 0;
    }

    if ($is_debug) {
      add_header X-Cache-File $cachefile;
      add_header X-Cache-File $gzipcachefile;
    }

    try_files $gzipcachefile $cachefile $uri $uri/ /index.php?$args;
  }


The problem is that with this design, I get a 404 error, most likely due to IF. I couldn't find a similar example and can't figure out what's wrong here.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
edo1h, 2020-07-23
@edo1h

Something like that:

map $http_x_forwarded_for $cachefile_header {
    "8.8.8.8"    $cachefile;
    default      "";
}
…

server {
    …
    location "/" {
        …
        add_header X-Cache-File $cachefile_header;
    }
}

P.S. good article about map (it also mentions "if is evil")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question