rewrite
The `rewrite` directive modifies the URI of a request based on specified patterns and replacement strings.
Description
The rewrite directive in NGINX is used to change the URI of incoming requests based on specific regular expression patterns. This directive can be particularly useful for URL redirection or for reworking URLs for cleaner, user-friendly access. The directive takes two or three arguments: the first is a regular expression pattern that will be matched against the incoming request URI, the second is the replacement string to change the URI to, and the optional third argument specifies the flag that determines whether the rewrite is performed in the current request context or if it leads to a new request, also known as a redirect.
When the rewrite directive is executed, NGINX evaluates the incoming request URI against the specified regular expression. If a match is found, it replaces the matched portion with the replacement string, effectively rewriting the URI. If a redirect flag like last, break, or redirect is used, NGINX will handle subsequent processing according to that flag's behavior. For example, last will stop processing the rewrite and continue with the new URI, while break will stop processing the current set of directives, and redirect will send a 302 response forcing the client to navigate to the new URI.
Misconfigured regular expressions or incorrect use of flags can lead to unexpected behavior or looping rewrites, so careful attention to the syntax and logic is necessary when using this directive.
Config Example
rewrite ^/oldpath/(.*)$ /newpath/$1 permanent;
Ensure that the regular expression accurately matches the intended URI as performance can degrade with overly complex patterns.
Using the redirect flag initiates a full client redirect which may be inappropriate for internal rewrites.
Care should be taken to avoid infinite rewrite loops by ensuring that the rewritten URI does not match the rewrite rule again.