Rewrite rules with NGinx

Francis Daly francis at
Sun Jan 20 17:01:00 UTC 2013

On Sun, Jan 20, 2013 at 04:35:39PM +0000, Mik J wrote:

Hi there,

> >   location = /nginx {
> >    # proxy_pass or fastcgi_pass and fastcgi_param, or whatever is appropriate
> >   }
> > 
> > "appropriate" depends on which non-nginx thing you use to process php.
> I have not installed anything like that at the moment but I'll use fastcgi I think. I'm not sure I fully understand your answer though.

Apache "does" php internally (typically). Nginx "does" php by being a
client to some other server that "does" php itself. You need to configure
nginx to send the right requests to that other server.

For fastcgi, the usual way to tell the fastcgi server which file it
should process is by sending something like (in this case)

  fastcgi_param SCRIPT_FILENAME $document_root/page.php;

and since you also want to use a particular query string:

  fastcgi_param QUERY_STRING arg=nginx;

No need for a rewrite.

> According to your answer I should write something like this
> location = /page.php {
> if ($arg_arg = nginx) {
>      return 302 /nginx;
>      }
> # proxy_pass or fastcgi_pass, or whatever is appropriate
> }

Yes; that will redirect /page.php?k1=v1&arg=nginx&k2=v2 to /nginx (for
any k1, v1, k2, v2).

And then you'll want to add the rest of the configuration for any
/page.php request that does not match that "if".

> > What should happen for /page.php?arg=other ?
> I didn't think about this case but if arg=other, I would like the redirection to go to

When you start handling more than one case specially, it is probably
time to use a "map" to map between inputs and desired outputs.

Or just let the page.php script do the logic to appropriately handle
the arguments.

> > And for /page.php?arg=nginx&other?
> I'm not sure I understand but the arguements provided will be arg=nginx&language=ru. So yes there could be more than one argument.

If you don't care about other arguments, then $arg_arg is the variable
to use.

If you care that there is only one argument, then $query_string is the
variable to use.

> But my Apache setting has only one argument at the moment and I'd like to move from Apache to Nginx.

You'll need to move to something like nginx + fastcgi.

The hard part of migrations is usually deciding exactly what behaviours
you do and do not want. Once you know that, it should be straightforward
to have a test system which will show you that your current attempt does
or does not match the requirements.

Good luck with it,

Francis Daly        francis at

More information about the nginx mailing list