Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return 200 by Nginx without serving a file

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;
}
like image 760
Keke Avatar asked Oct 18 '25 23:10

Keke


1 Answers

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.

like image 58
Komu Avatar answered Oct 20 '25 17:10

Komu