Mastering Nginx

(Ron) #1

Rewrite Rule Guide


[ 274 ]

Of course, what is inside the location context is dependent upon your setup, but the


principle remains the same; matches against the URI are best served by a location.


This principle also applies to RewriteRules that have an implicit REQUEST_URI. These
are typically bare RewriteRules that transform the URI from an older format to a


newer one. In the following example, we see that the show.do is no longer necessary:


RewriteRule ^/controller/show.do$ http://example.com/controller
[L,R=301]

This translates to an NGINX configuration as follows:


location = /controller/show.do {

rewrite ^ http://example.com/controller permanent;

}

Not to get too carried away with creating locations whenever we see a RewriteRule,


we should keep in mind that regular expressions translate directly.


Rule #3: Replace matches against HTTP_HOST with a server


Related closely to Rule #2, this rule takes configurations into account that try to either


remove or add a www onto a domain name. These types of rewrite rules are often
found in .htaccess files or in virtual hosts with overloaded ServerAliases:


RewriteCond %{HTTP_HOST} !^www

RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

Here, we translate the case where no www is found at the beginning of the Host part
of the URL to the variant with a www there:


server {

server_name example.com;

rewrite ^ http://www.example.com$request_uri permanent;

}
Free download pdf