How to Use return Directive in Nginx for Redirects and Responses
In Nginx, the
return directive immediately stops processing and sends a specified HTTP status code and optional URL or text back to the client. It is commonly used for simple redirects or to return custom status codes and messages.Syntax
The return directive syntax is simple and flexible. It can be used with just a status code or with a status code and a URL or text message.
return <code>: Sends only the HTTP status code.return <code> <text_or_url>: Sends the status code and a redirect URL or custom text.
This directive is placed inside server, location, or if blocks.
nginx
return 404; return 301 https://example.com/; return 200 "Hello, world!";
Example
This example shows how to use return to redirect all requests to a new domain and how to return a custom 404 message.
nginx
server {
listen 80;
server_name oldsite.com;
# Redirect all requests to newsite.com
location / {
return 301 https://newsite.com$request_uri;
}
# Custom 404 page
location = /404.html {
return 404 "Page not found";
}
}Output
When accessing oldsite.com, the browser is redirected to https://newsite.com with the same path.
Accessing /404.html returns a 404 status with the text "Page not found".
Common Pitfalls
Common mistakes when using return include:
- Using
returninsideifblocks incorrectly, which can cause unexpected behavior. - Forgetting to include the full URL in redirects, leading to broken redirects.
- Using
returnwith a status code but no content for error pages, which may confuse users.
Always test redirects and custom responses to ensure they behave as expected.
nginx
## Wrong: Missing full URL in redirect
location /old {
return 301 /new;
}
## Right: Full URL with $request_uri
location /old {
return 301 https://example.com/new$request_uri;
}Quick Reference
| Usage | Description | Example |
|---|---|---|
| return <code> | Send only HTTP status code | return 404; |
| return <code> <URL> | Redirect to URL with status | return 301 https://example.com$request_uri; |
| return <code> <text> | Return status with custom text | return 200 "OK"; |
Key Takeaways
Use
return to quickly send HTTP status codes or redirects in Nginx.Always include full URLs in redirects to avoid broken links.
Avoid complex logic inside
if blocks with return to prevent unexpected behavior.Test your
return directives to ensure they produce the desired response.Place
return inside server, location, or if blocks as needed.