The line location = /user.php asks Nginx to check for the prefix'/user'. As said earlier, the Nginx will search for phrases between the start and end notations as ^ and $ along with the non-greedy '?' modifier. The phrase in our example is a range of users. It is mentioned inside the square brackets as [0-9]+. The back-reference in this expression is noted within the parenthesis and is referred to by the $1 symbol. So, for our example, the rewrite will happen for all users automatically.
One special case under the dynamic reference is the multiple back-references.
Now, we have discussed how to write the rewrite rules for simple and complex URLs.
Understand the detailed working of rewrite rules through some examples handling various scenarios.
Directive Comparison
Let's analyze both directives by comparing them and find out why the rewrite derivative is more powerful.
Return directive
- It is simple to use and understand.
- It can be used in both server and location contexts.
- It explicitly mentions the corrected or updated URL so that the client can use them in the future.
- Return directives can include multiple error codes as well.
- For codes 301, 302, 303, and 307, the URL parameters define the redirect URL.
return (301 | 302 | 303 | 307) url;
- For other codes, the text is to be explicitly mentioned by the user.
return (1xx | 2xx | 4xx | 5xx) ["text"];
For example: return 401 "Access denied because the token is expired or invalid";
- This directive can be used in scenarios where the return URL is correct for both server and location block, and rewritten URL is built with Nginx variables.
Rewrite directive
- It can accommodate more complex URL modifications where capturing elements without Nginx variables or an update in the elements in the path is required.
- It can be used in both server and location contexts.
- The rewrite directive can return only code 301 or 302. To accommodate other codes, explicitly add the return directive after the rewrite directive.
- It may not send the redirect details to the client.
- The Nginx request processing is not halted.
Conclusion
The return and rewrite directives can be used to redirect URLs in both server and location contexts. Though the return directive is much simpler, the rewrite directive is widely used as it can also handle complex modifications/updates to the URLs.