0

I am writing a location block for a Nginx config, and it is for URIs with pattern like this: www.mysite.com/a/b/blah/c or www.mysite.com/a/b/blah/c/n.

Where a and b are fixed, blah may vary, c can be one of three fixed strings (optionA, optionB, optionC) only, and n is a digit starting from 0, 1, 2, and so on. In addition, n is valid only when c is equal to optionB, so that in any other case Nginx should throw a 404 immediately if there is anything after c.

I intend to write a location block as:

location ^~ /a/b/ {
    ...
}

The logic I want to implement inside this location: first capture c from a given URI, and based on its value, do one of three possible rewrites. i.e.

if (c = optionA) {
    rewrite ... ... break;
}

if (c = optionB) {
    rewrite ... ... break;
}

if (c = optionC) {
    rewrite ... ... break;
}

My questions are:

  1. I have read that if statement should be generally avoided in location block in Nginx, but it seems like its use with rewrite is an exception. Will the way I use rewrite here cause any problem?

  2. How do I capture c and implement the conditional rewrite logic here?

1 Answer 1

1

use regexp, something like: www.mysite.com/(.)/(.)/blah/c and $1, $2 for founded url's parts.

2
  • thanks for the suggestion. But where do I do this regex? If I do at location matching level, will the resulting variables $1, $2, etc conflict with the ones resulting from the regex match for the rewrite within each if statement inside the location block?
    – MLister
    Dec 4, 2012 at 15:01
  • 2
    just look at examples on the official site of nginx: nginx.org/ru/docs/http/ngx_http_rewrite_module.html
    – alterpub
    Dec 5, 2012 at 12:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .