Mastering Nginx

(Ron) #1

Rewrite Rule Guide


This appendix is meant to introduce the rewrite module in NGINX and serve as a


guide for creating new rules as well as translating legacy Apache rewrite rules into
NGINX's format. In this appendix, we will discuss the following:



  • Introducing the rewrite module

  • Creating new rewrite rules

  • Translating from Apache


Introducing the rewrite module


NGINX's rewrite module is a simple regular expression matcher combined with
a virtual stack machine. The first part of any rewrite rule is a regular expression.


As such, it is possible to use parentheses to define certain parts as "captures", which
can later be referenced by positional variables. A positional variable is one in which


its value depends on the order of the capture in the regular expression. They are


labeled by number, so positional variable $1 references what is matched by the first
set of parentheses, $2 the second set, and so on. For example, refer to the following


regular expression:


^/images/([a-z]{2})/([a-z0-9]{5})/(.*)\.(png|jpg|gif)$

The first positional variable, $1, references a two-letter string which comes immediately
after the string /images/ at the beginning of the URI. The second positional variable,


$2, refers to a five character string composed of lowercase letters and the numbers
from 0 to 9. The third positional variable, $3, is presumably the name of a file. And the


last variable to be extracted from this regular expression, $4, is one of png, jpg, or gif,


which appears at the very end of the URI.

Free download pdf