primary and fallback to backup -- try_files, proxy_pass, upstream?

Denis Arh denis at
Sun Feb 14 15:43:55 MSK 2010

What I would like to have is nginx first to try primary service and then to
fallback to the backup if primary is not available.

What I've tried:

1. try_files:

    location /api {
        try_files @primary @backup;

    location @primary {
        proxy_pass http://localhost:81;

    location @backup {
        include        /etc/nginx/fastcgi_params;
        fastcgi_param  SCRIPT_FILENAME  $document_root/boot/api.php;
        fastcgi_pass   unix:/tmp/php-fpm.sock;

This results in nginx only invoking @backup.
If I switch try_files params (try_files @backup @primary) then @primary is
invoked but in case it's not running I get 502 error (error log: 9228#0:
*1850 no live upstreams while connecting to upstream).

2. upstream

upstream backend {
    server localhost:81;
    server unix:/tmp/php-fpm.sock;

location /api {
   proxy_pass http://backend;

The first part of this solution works -- requests are first passed to
localhost:81 and handled there without any problems and if this one is down
requests go to the second server in the upstream.
What happens there is another 502 error:
error-log: *1840 recv() failed (104: Connection reset by peer) while reading
response header from upstream, client: ......, server: ......, request: "GET
/api HTTP/1.1", upstream: "http://unix:/tmp/php-fpm.sock:/api"

How to configure fastcgi backend propery to handle this properly?

Is there any way to make this work?
If both are possible, which one is better?

Denis Arh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the nginx mailing list