1

I wrote this /etc/nginx/conf.d/apply.conf and started nginx.

server {
  location = /hoge {
    return 200;
  }
}

but the curl command fails.

curl localhost:80/hoge

It says

<html>
<head><title>404 Not Found</title></head>
<body bgcolor="white">
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.13.9</center>
</body>
</html>

and the logs are

open() "/usr/share/nginx/html/hoge" failed (2: No such file or directory), client: 127.0.0.1, server: localhost, request: "GET /hoge HTTP/1.1", host: "localhost"

I want to just return the status code without response body or with response body blank.

I changed to this but still not working.

location /hoge {
return 200 'Wow';
add_header Content-Type text/plain;
}

also tried this.

location /hoge {
return 200 'Wow';
default_type text/plain;
}
Geuis
  • 41,122
  • 56
  • 157
  • 219
Keke
  • 71
  • 1
  • 2
  • 5
  • 1
    The `location` block is fine, but you are putting it into the wrong `server` block. See [how `nginx` processes a request](http://nginx.org/en/docs/http/request_processing.html) for more. – Richard Smith Feb 25 '18 at 09:08
  • Thanks. I found the reason why it wasn't working and it was how you said. – Keke Feb 25 '18 at 11:44
  • @KeKe Could you please post what the reason was, it would be helpful. I am facing the same issue, tried all the things you have posted plus few more but still unable to figure out what the issue is. – Vijay Kalidindi Nov 19 '19 at 11:26

2 Answers2

8

It is hard to say without context(how your entire nginx config file looks like), because of how nginx processes a request

A config file like the following, should work just fine for what you are looking for:

  server {
    listen 80;

    location /hoge {
      return 200;
    }

  }

However, if your config file has other location blocks(especially if they are regex based) then you may not get the expected solution. Take an example of this config file:

  server {
    listen 80;

    location /hoge {
      return 200;
    }

    location ~* /ho {
      return 418;
    }

  }

Sending a request to curl localhost:80/hoge would return a http status code 418 instead of 200. This is because the regex location matched before the exact location.

So, the long answer is; it is hard to tell without the context of the whole nginx conf file that you are using. But understanding how nginx processes a request will get you to the answer.

Komu
  • 14,174
  • 2
  • 28
  • 22
0

Complementary answer to the post of Komu:

  • When returning nothing, you should use "return 204" instead of "return 200" ; This is useful to answer to the "OPTIONS" method ;
  • The return statement must be the last one so your should place "default_type" and "add_header" statements before the return.
Erwan
  • 11
  • 3