Score:0

nginx location directive does not return http status

us flag

Note: I have read through the several Q/A's on SO, ServerFault, etc... but none of the answer seem to be working.

Running an AWS ec2 Ubuntu (v20.04) web server with a basic nginx (v1.18) config. However, the location directive for /a-custom-path returning an http status code of 200 is never processed and/or is processed and ignored.

Here's the config:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;

    location /a-custom-path {
      access_log off;
      add_header Content-Type text/plain;
      return 200 'OK';
    }

    access_log /var/log/nginx/unknown.log;
    return 412;
}

The location /a-custom-path is never returning a 200 status; it always falls through to the 412 response. I've tried various location directives such as:

location /a-custom-path
location /a-custom-path/
location = /a-custom-path
location = /a-custom-path/

However, they all have the same behavior of falling through to the 412 response.

Question
How can I create a custom location path that returns a 200 response and all other requests return a 412 response?

Edit - Revised & Working Config

For anyone else finding this question, here is the final working solution based on the accepted answer:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;

    # everything except '/a-custom-path' gets a 412 response
    location / {
      return 412;
    }

    location /a-custom-path {
      return 200 'OK';
      access_log off;
      add_header Content-Type text/plain;
    }

    access_log /var/log/nginx/unknown.log;
}
Score:1
za flag

Because things get nasty when you use returns not bound to any location {}. Put your return 412 inside location / {} and there will be happiness and joy.

P.S. When your web-server returns empty answer, you should use 204 status, not 200. Both will work, but 204 shows you know things.

us flag
Thanks. I'm from a Windows background and just assumed the `return` statement was a short-circuit and exited the config. Added a specific `location / { } ` block and all is well.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.