Nginx · The edge of your stack
When should you use rewrite and when should you use return?
Short answer
Use return for redirects and fixed status responses because it stops processing immediately. Use rewrite only when you need to transform the URI, and prefer last or break deliberately because rewrites can loop.
return is a terminal directive. It sends a status or redirect and stops processing the current request. rewrite changes the URI and may cause another location lookup, which makes it more powerful and easier to misuse.
server {
listen 80;
server_name old.example.com;
return 301 https://new.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 /legacy/ {
rewrite ^/legacy/(.*)$ /v2/$1 permanent;
}
location /docs {
rewrite ^/docs/(.*)$ /documentation/$1 last;
}
}Rewrite flags
- last stops the current rewrite set and searches for a new location
- break stops rewriting but keeps the current location
- redirect returns a 302; permanent returns a 301
- Without a flag, processing continues with the next rewrite directive
- A rewrite loop eventually fails with an internal redirection cycle
For a simple host or path migration, return is clearer and cheaper. Reach for rewrite when the new path depends on captured groups, and keep the regex anchored so it cannot match more than intended.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between rewrite last and rewrite break?
- 2Why can a rewrite produce an internal redirection cycle?
- 3When is return inside an if block acceptable?
- 4How do you preserve query strings across a rewrite?
Say it in the interview
I use return for redirects and fixed responses because it terminates processing and is easy to reason about. I use rewrite when I actually need to transform a URI with captures, and I choose last or break based on whether location matching should run again. I keep regexes anchored and avoid if blocks for routing logic. If a rewrite loops, Nginx eventually returns an internal redirection cycle error.
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.