Rewrite vs Return in Nginx: Key Differences and Usage
rewrite changes the URL and can continue processing other rules or locations, while return immediately sends a response or redirect to the client, stopping further processing. Use rewrite for internal URL changes and return for quick redirects or responses.Quick Comparison
This table summarizes the main differences between rewrite and return directives in Nginx.
| Factor | rewrite | return |
|---|---|---|
| Purpose | Modify URL and optionally redirect | Send immediate response or redirect |
| Processing | Continues processing after rewrite | Stops processing immediately |
| Use Case | Internal URL changes, complex rewrites | Simple redirects or status responses |
| Syntax Complexity | Supports regex and variables | Simple status code and URL |
| Performance | Slightly slower due to processing | Faster, direct response |
| Effect on Client | May or may not redirect client | Always sends response to client |
Key Differences
The rewrite directive in Nginx is used to change the requested URL based on patterns. It supports regular expressions and variables, allowing complex URL transformations. After rewriting, Nginx can continue processing other directives or locations, which means the client might not see a redirect if last or break flags are not used.
On the other hand, return immediately stops processing and sends a response to the client. This response can be a status code like 301 or 404, optionally with a URL for redirection. Because it ends processing, it is simpler and faster for straightforward redirects or error responses.
In summary, use rewrite when you need to internally change URLs or apply complex rules, and use return when you want to quickly send a redirect or status code without further processing.
Rewrite Example
server {
listen 80;
server_name example.com;
location /oldpath/ {
rewrite ^/oldpath/(.*)$ /newpath/$1 permanent;
}
}Return Equivalent
server {
listen 80;
server_name example.com;
location /oldpath/ {
return 301 /newpath/$1;
}
}When to Use Which
Choose rewrite when you need to change URLs internally or apply complex pattern matching before deciding the final URL. It is useful for legacy URL support or URL restructuring without immediate client redirection.
Choose return when you want to quickly send a redirect or status code to the client, such as permanent redirects (301), temporary redirects (302), or error responses. It is simpler, faster, and clearer for straightforward responses.
Key Takeaways
rewrite modifies URLs and can continue processing other rules.return immediately sends a response or redirect and stops processing.rewrite for complex URL changes and internal routing.return for simple, fast redirects or status responses.return is generally faster and clearer for client redirects.