Mastering Nginx

(Ron) #1

Rewrite Rule Guide


[ 270 ]

Directive Explanation
rewrite Changes the URI from one matched by the
regular expression in the first parameter to
the string in the second parameter. If a third
parameter is given, it is one of the following
flags:


  • last: stops processing the rewrite
    module directives and searches for a
    location matched by the changed URI

  • break: stops processing the
    rewrite module directives

  • redirect: returns a temporary
    redirect (code 302), used when the
    URI does not begin with a scheme

  • permanent: returns a permanent
    redirect (code 301)
    rewrite_log Activates the notice level logging of
    rewrite to errorlog.
    set Sets a given variable to a specific value.
    unitialized

    variable_warn


Controls whether or not warnings about
uninitialized variables are logged.

Creating new rewrite rules


When creating new rules from scratch, just as with any configuration block, plan out
exactly what needs to be done. Some questions to ask yourself are as follows:



  • What pattern(s) do I have in my URLs?

  • Is there more than one way to reach a particular page?

  • Do I want to capture any parts of the URL into variables?

  • Am I redirecting to a site not on this server, or could my rule be seen again?

  • Do I want to replace the query string arguments?


In examining the layout of your website or application, it should be clear what


patterns you have in your URLs. If there is more than one way to reach a certain


page, create a rewrite rule to send a permanent redirect back to the client. Using
this knowledge, you can construct a canonical representation of your website or


application. This not only makes for cleaner URLs, but also helps your site to be
found more easily.

Free download pdf