Mastering Nginx

(Ron) #1

Rewrite Rule Guide


[ 266 ]

The second part of a rewrite rule is the URI to which the request is rewritten. The URI


may contain any positional variable captured in the regular expression indicated by
the first argument, or any other variable valid at this level of NGINX's configuration:


/data?file=$3.$4

If this URI does not match any of the other locations in the NGINX configuration,
then it is returned to the client in the Location header with either a 301 (Moved


Permanently) or a 302 (Found) HTTP status code indicating the type of redirect


that is to be performed. This status code may be specified explicitly if permanent
or redirect is the third parameter.


This third parameter to the rewrite rule may also be either last or break, indicating
that no further rewrite module directives will be processed. Using the last flag will


cause NGINX to search for another location matching the rewritten URI.


rewrite '^/images/([a-z]{2})/([a-z0-9]{5})/(.*)\.(png|jpg|gif)$' /
data?file=$3.$4 last;

The break parameter may also be used as a directive on its own, to stop rewrite


module directive processing within an if block or other context in which the
rewrite module is active. The following snippet presumes that some external


method is used to set the $bwhog variable to a non-empty and non-zero value


when a client has used too much bandwidth. The limit_rate directive will then
enforce a lower transfer rate. break is used here because we entered the rewrite


module with if, and we don't want to process any further such directives:


if ($bwhog) {

limit_rate 300k;

break;

}

Another way to stop the processing of the rewrite module directives is to return


control to the main http module processing the request. This may mean that
NGINX returns information directly to the client, but return is often combined with


an error_page to either present a formatted HTML page to the client or activate a


different module to finish processing the request. The return directive may indicate
a status code, a status code with some text, or a status code with a URI. If a bare URI


is the sole parameter, then the status code is understood to be a 302. When the text
is placed after the status code, that text becomes the body of the response. If a URI is


used instead, then that URI becomes the value of the Location header, to which the


client will then be redirected.

Free download pdf