Mastering Nginx

(Ron) #1
Appendix B

[ 267 ]

As an example, we want to set a short text as the output for a file not found error in


a particular location. We specify the location with an equals sign (=) to exactly match
just this URI:


location = /image404.html {

return 404 "image not found\n";

}

Any call to this URI would then be answered with an HTTP code of 404, and the
text image not found\n. So, we can use /image404.html at the end of a try_files


directive or as an error page for image files.


In addition to directives relating to the act of rewriting a URI, the rewrite module


also includes the set directive to create new variables and set their values. This is
useful in a number of ways, from creating flags when certain conditions are present,


to passing named arguments on to other locations and logging what was done.


The following example demonstrates some of these concepts and the usage of the


corresponding directives:


http {

# a special log format referencing variables we'll define later
log_format imagelog '[$time_local] ' $image_file ' ' $image_type '
' $body_bytes_sent ' ' $status;

# we want to enable rewrite-rule debugging to see if our rule does
# what we intend
rewrite_log on;

server {

root /home/www;

location / {

# we specify which logfile should receive the rewrite-rule
debug
# messages
error_log logs/rewrite.log notice;

# our rewrite rule, utilizing captures and positional
variables
Free download pdf