Mastering Nginx

(Ron) #1

Rewrite Rule Guide


[ 272 ]

location /images/ {

rewrite ^(/images)/(.*)\.(png|jpg|gif)$ $1/$3/$2.$3 break;

}

}

Passing new query string arguments as part of a rewrite rule is one of the objectives
of using rewrite rules. However, when the initial query string arguments should be


discarded, and only the ones defined in the rule should be used, a? character needs
to be placed at the end of the list of new arguments.


rewrite ^/images/(.*)_(\d+)x(\d+)\.(png|jpg|gif)$ /resizer/$1.$4?width
=$2&height=$3? last;

Translating from Apache


There is a long history of writing rewrite rules for Apache's powerful mod_rewrite


module, and most resources on the Internet are focused on these. When encountering
rewrite rules in Apache's format, they can be translated into a form that NGINX can


parse by following a few simple rules.


Rule #1: Replace directory and file existence checks with try_files


When encountering an Apache rewrite rule of the following form:


RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?q=$1 [L]

This can best be translated into an NGINX configuration as follows:


try_files $uri $uri/ /index.php?q=$uri;

These rules state that when the filename specified in the URI is neither a file nor
a directory on disk, the request should be passed to the index.php file lying in


the current context's root and given the argument q with a value matching the


original URI.

Free download pdf