Captures

One last feature of the regular expression mechanism is the ability to capture sub-expressions. Whatever text is placed between parentheses ( ) is captured and can be used after the matching process. The captured characters become available under the form of variables called $N, where N is a numeric index, in order of capture. Alternatively, you can attribute an arbitrary name to each of your captures (see the following example). The variables generated through the captures can be inserted within directive values.

Here are a couple of examples to illustrate the principle:

Pattern

Example of a matching string

Captured

^(hello|hi) (sir|mister)$

hello sir

$1 = hello

$2 = sir

^(hello (sir))$

hello sir

$1 = hello sir
$2 = sir

^(.*)$

nginx rocks

$1 = nginx rocks

^(.{1,3})([0-9]{1,4})([?!]{1,2})$

abc1234!?

$1 = abc

$2 = 1234

$3 = !?

Named captures are also supported through the following syntax:

?<name>

Example: ^/(?<folder>[^/]+)/(?<file>.*)$

/admin/doc

$folder = admin

$file = doc

 

When you use a regular expression in Nginx, for example, in the context of a location block, the buffers that you capture can be employed in later directives:

server { 
    server_name website.com; 
    location ~* ^/(downloads|files)/(.*)$ { 
        add_header Capture1 $1; 
        add_header Capture2 $2; 
    } 
}

In the preceding example, the location block will match the request URI against a regular expression. A few of URIs that would apply here: /downloads/file.txt, /files/archive.zip, or even /files/docs/report.doc. Two parts are captured: $1 will contain either downloads or files, and $2 will contain whatever comes after /downloads/ or /files/. Note that the add_header directive (syntax: add_header header_name header_value, see the HTTP headers module section) is employed here to append arbitrary headers to the client response, for the sole purpose of demonstration.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.117.105