How can I rewrite a URL in nginx after matching the location?

Member

by armani , in category: Other , a year ago

How can I rewrite a URL in nginx after matching the location?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jerrod , a year ago

@armani 

You can use the rewrite directive in nginx to perform URL rewriting. The rewrite directive allows you to redirect or change the URL based on conditions specified in the location block.


Here's an example that matches a URL and rewrites it:

1
2
3
location /example/ {
    rewrite ^/example/(.*)$ /new/$1 permanent;
}


In this example, the location block matches any URL that starts with /example/. The rewrite directive then takes the matched URL (/example/(.*)$) and rewrites it to /new/$1 where $1 is a backreference to the captured value in the matched URL (i.e. the value matched by (.*)). The permanent flag at the end specifies that this should be a permanent redirect (HTTP status code 301).


You can also specify conditions for the rewrite directive, for example:

1
2
3
4
5
location /example/ {
    if ($arg_test) {
        rewrite ^/example/(.*)$ /new/$1 permanent;
    }
}


In this example, the rewrite will only occur if the URL contains the test argument (e.g. /example/?test).