return

The `return` directive immediately returns a specified HTTP status code or redirect response to the client.

Syntaxreturn code | code url;
Defaultnone
Contextserver, location, if in server, if in location
Arguments1-2

Description

The return directive is a versatile feature of NGINX that allows you to send HTTP responses from various contexts within the server or location block. It can take one or two arguments: the first argument specifies the HTTP status code (e.g., 200, 404, 301), and the optional second argument can provide a URL for redirection. When the directive is executed, it immediately terminates the request processing, discarding any further configuration or processing steps. This makes it useful for simplifying responses without needing complex configurations or logic.

In the case where a status code is provided without a URL, a simple response is returned to the client with the specified status code. If a redirect is required, you may specify a status code like 301 (Moved Permanently) along with the new URL. This instruction is processed within the given context but can also be chained with other directives when used in conditional statements (i.e., within if blocks). Combining return within a conditional allows for more dynamic response behavior based on request parameters or headers.

Config Example

location /old-path {
    return 301 https://example.com/new-path;
}

location /not-found {
    return 404;
}

Using return within the if directive can yield unexpected behaviors if not carefully structured. Be cautious of NGINX's handling of if blocks.

When using a redirect with a relative path, ensure the URL begins with http:// or https:// to avoid undesired behavior, as relative paths may lead to local redirects that confuse clients.

← Back to all directives