How to Redirect 302 in Nginx: Simple Guide
To create a 302 redirect in Nginx, use the
return 302 URL; directive inside a server or location block. This tells Nginx to send a temporary redirect response to the client, pointing to the new URL.Syntax
The basic syntax to perform a 302 redirect in Nginx is:
return 302 URL;: Sends a temporary redirect to the specified URL.- This directive is placed inside a
serverorlocationblock.
nginx
return 302 https://example.com/newpage;
Example
This example shows how to redirect all requests from http://oldsite.com to https://newsite.com temporarily using a 302 redirect.
nginx
server {
listen 80;
server_name oldsite.com;
location / {
return 302 https://newsite.com$request_uri;
}
}Output
When a user visits http://oldsite.com/page, the browser receives a 302 redirect to https://newsite.com/page and temporarily redirects there.
Common Pitfalls
Common mistakes when setting up 302 redirects in Nginx include:
- Using
rewritewithout thelastflag, which may cause unexpected behavior. - Forgetting to include
$request_urito preserve the original path and query string. - Confusing 302 (temporary) with 301 (permanent) redirects, which have different caching effects.
Correct usage ensures the redirect is temporary and the client knows not to cache it permanently.
nginx
## Wrong way (may cause issues):
location / {
rewrite ^ https://newsite.com$request_uri last;
}
## Right way:
location / {
return 302 https://newsite.com$request_uri;
}Quick Reference
Summary tips for 302 redirects in Nginx:
- Use
return 302 URL;for simple temporary redirects. - Place the directive inside
serverorlocationblocks. - Include
$request_urito keep the original path and query. - Use 302 for temporary redirects to avoid caching by browsers.
Key Takeaways
Use
return 302 URL; inside server or location blocks for temporary redirects.Include
$request_uri to preserve the original request path and query string.302 redirects tell browsers the redirect is temporary and should not be cached permanently.
Avoid using
rewrite without proper flags for redirects to prevent unexpected results.Test redirects by visiting the old URL and checking the HTTP status code and Location header.