Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

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

share|improve this answer
    
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 '12 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 '12 at 12:55

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.