Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am writing a location block for a Nginx config, and it is for URIs with pattern like this: or

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
up vote 1 down vote accepted

use regexp, something like: 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
just look at examples on the official site of nginx: – alterpub Dec 5 '12 at 12:55

Your Answer


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.