Mastering Nginx

(Ron) #1
Appendix B

[ 271 ]

For example, if you have a home controller to handle default traffic, but can also


reach that controller through an index page, you could have users getting to the
same information using the following URIs:


/
/home
/home/
/home/index
/home/index/
/index
/index.php
/index.php/

It would be more efficient to direct requests containing the name of the controller


and/or the index page back to the root:


rewrite ^/(home(/index)?|index(\.php)?)/?$ $scheme://$host/ permanent;

We specified the $scheme and $host variables because we're making a permanent
redirect (code 301) and want NGINX to construct the URL using the same


parameters that reached this configuration line in the first place.


If you would like to be able to log individual parts of the URL separately, you can use


captures on the URI in the regular expression. Then, assign the positional variables to
named variables, which are then part of a log_format definition. We saw an example


of this in the previous section. The components are essentially as follows:


log_format imagelog '[$time_local] ' $image_file ' ' $image_type ' '
$body_bytes_sent ' ' $status;

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

set $image_file $3;

set $image_type $4;

access_log logs/images.log imagelog;

When your rewrite rule leads to an internal redirect or instructs the client to call a
location in which the rule itself is defined, special care must be taken to avoid a rewrite


loop. For example, a rule may be defined in the server context with the last flag, but
must use the break flag when defined within the location it references.


server {

rewrite ^(/images)/(.*)\.(png|jpg|gif)$ $1/$3/$2.$3 last;
Free download pdf