Map directive not working: unknown variable

I'm using nginx version 1.4.6.

I'm having trouble getting map to work. I have something like this:

http {
    map $arg_f $forum {
        default 0;
        1 2;
    }

    # ...

    server {
        # ...

        location = /old.php {
            if ($forum) {
                return 301 /forums/$forum/;
            }
            return 494;
        }

        # ...
    }

    # ...
}

Here's what I get with nginx -t:

nginx: [emerg] unknown "forum" variable

The goal is to map old URIs to new URIs. The catch is that some of the numeric forum IDs have changed. I'd like to handle this in Nginx, so I'm willing to resort to lua if there's no other easy way. I'm open to alternative solutions as long as they're elegant, but I'd like to know why map isn't working here. Is it because the rewrite module doesn't query maps, at least in 1.4?


Solution 1:

I just tested the following minimal configuration with nginx v1.4.7:

events {
    worker_connections  1024;
}


http {
    map $arg_f $forum {
        default 0;
        1 2;
    }

    server {
        location = /old.php {
            default_type  text/html;
            if ($forum) {
                return 200 "OK";
            }
            return 200 "KO";
        }
    }
}

It runs flawlessly, so the most probable cause of your trouble is that your configuration is not applied correctly. I would guess that changes you made on the side of adding the map directive broke it, making the forum variable inexistent.

Try to:

  1. Use nginx -t to validate your configuration
  2. Monitor your error log file while you issue service nginx reload to catch any error that might happen at runtime which are undetectable at configuration time.

As a side note, keep in mind that using up-to-date product is always a good idea.

  • At the very least, use nginx v1.4.7 Changelog
  • Even better, use at least the stable version (currently being v1.6.2) Changelog

http://nginx.org/en/download.html