Nginx · The edge of your stack
How do you implement redirects correctly?
Short answer
Use 301 or 308 for permanent redirects and 302 or 307 for temporary ones. 307 and 308 preserve the request method, and permanent redirects are cached aggressively by browsers.
The status code communicates permanence and method handling. A 301 or 302 may be rewritten to GET by some clients, while 307 and 308 preserve the original method and body. That matters for API endpoints.
server {
listen 80;
server_name example.com www.example.com;
return 301 https://example.com$request_uri;
}
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/nginx/tls/example.com.crt;
ssl_certificate_key /etc/nginx/tls/example.com.key;
location = /pricing {
return 308 https://example.com/plans;
}
}Choosing a code
- 301 permanent: cacheable, common for HTTP to HTTPS and domain migration
- 302 temporary: not meant to be cached long term
- 307 temporary and method-preserving: use for temporary API moves
- 308 permanent and method-preserving: use when the move is permanent
- Avoid redirect chains because each hop adds latency and failure risk
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between 301 and 308?
- 2When would you use 302 instead of 301?
- 3How do you preserve the query string in a redirect?
- 4Why are permanent redirects risky during an experiment?
Say it in the interview
I choose the redirect code based on permanence and method preservation. 301 and 308 are permanent; 302 and 307 are temporary, and 307 plus 308 preserve the method and body. I use $request_uri when migrating a host so the path and query string survive. I avoid chains and am careful with permanent redirects because browsers cache them aggressively.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Nginx mock interview and get scored feedback on depth, clarity and confidence.