4

This is a nginx configuration

server {
    listen $PORT;

    location ~ ^/documents/(.*)$ {
        proxy_pass http://127.0.0.1:5000/$1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location = /favicon.ico {
        return 204;
        access_log    off;
        log_not_found off;
    }
}

There are two use cases of the url /documents/:

POST to /documents/ for some processing or

GET to /documents/ping used by AWS ELB as health check

In cloudwatch log I got heap of pings entries as a result

enter image description here

What is the easiest way to ask nginx not to log the ping?

Anthony Kong
  • 2,976
  • 10
  • 53
  • 91

1 Answers1

7

Here's an easy way - add this location block.

 location ~ /documents/ping {
    proxy_pass http://127.0.0.1:5000/$1;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    access_log    off;
    log_not_found off;
}

There are probably cleaner ways. One is to define the shared contents of the two blocks as a file and include it, but for a one-off I wouldn't bother.

Note - don't use if statements unless you can't help it.

Update

If you want to do an include do something like this

location ~ ^/documents/(.*)$ {
  include /path/to/fragment.conf;
}

 location /documents/ping {
  include /path/to/fragment.conf;

  access_log    off;
  log_not_found off;
}

In the file fragment.conf

  proxy_pass http://127.0.0.1:5000/$1;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

Agree that the ~ wasn't necessary, but I don't think it would hurt either.

Tim
  • 30,383
  • 6
  • 47
  • 77
  • Would love to have a DRY solution. If you can show me some resources to how to do 'shared content' in nginx, it would be great. But I agree with you your solution is good enough for this small case. One more quick question: do I still need '~' in this case? What is this '~' for? – Anthony Kong Sep 18 '17 at 01:34
  • Answer updated. I think the ~ isn't helpful but doesn't hurt either, in theory removing it could increase performance by maybe 0.00001% – Tim Sep 18 '17 at 01:44
  • One can simply use `location /documents` and `location /documents/ping` over here, prefix match is enough here so one can avoid the additional cost of regex here. – Tero Kilkanen Sep 18 '17 at 10:41