others-How to just return a fixed string and 200 response without serving a file or proxying to upstream service in nginx?

1. Purpose

In this post, I would demo how to just return a simple 200 http response and a fixed string without serving a file or proxying to an upstream service. Just as follows:



2. The solution

You can do as follows:

  location /foo {
  	 return 200 'hello world';
  }


Then we can test with this command:

[email protected]  /etc/nginx/includes  curl http://localhost:81/foo
hello world#


Here we used the return directive in nginx, what is the syntax of return directive in nginx?

Syntax:	return code [text];
return code URL;
return URL;
Default:	—
Context:	server, location, if

The code is http response code.

The return code [text] would stop processing the request and returns the specified *code* to a client. The non-standard code 444 closes a connection without sending a response header.

Starting from version 0.8.42, it is possible to specify either a redirect URL (for codes 301, 302, 303, 307, and 308) or the response body *text* (for other codes). A response body text and redirect URL can contain variables. As a special case, a redirect URL can be specified as a URI local to this server, in which case the full redirect URL is formed according to the request scheme ($scheme) and the server_name_in_redirect and port_in_redirect directives.

In addition, a *URL* for temporary redirect with the code 302 can be specified as the sole parameter. Such a parameter should start with the “http://”, “https://”, or “$scheme” string. A *URL* can contain variables.

3. Summary

In this post, I demonstrated how to return a fixed string instead of serving a file or proxying to upstream service in nginx, the key point is to use the return code [text] . That’s it, thanks for your reading.

-->