What is the difference between using upstream and location for php-fpm?

Solution 1:

location is used to match expressions and create rules for them.

upstream defines servers that can be referenced to.

In your example this means if you want to get an equivalent for

location ~ \.php$ {
    try_files      $uri = 404;
    fastcgi_pass   unix:/run/php-fpm/php-fpm.sock;
    fastcgi_index  index.php;
    include        fastcgi.conf;
}

, you would need

upstream php {
    server         unix:/run/php-fpm/php-fpm.sock;
}
location ~ \.php$ {
    try_files      $uri = 404;
    fastcgi_pass   php;
    fastcgi_index  index.php;
    include        fastcgi.conf;
}

The benefit of the upstream block is that you can configure more than one server/port/service as upstream and distribute the traffic on them, for example like this:

upstream php {
    server 127.0.0.1:8080       max_fails=3 fail_timeout=30s;
    server 192.68.1.2     weight=5;
    server         unix:/run/php-fpm/php-fpm.sock;
}

You can find more information about this in the nginx documentation:

http://nginx.org/en/docs/http/ngx_http_upstream_module.html

Solution 2:

I have found that, as of nginx 1.6.2 at least, the working syntax for me for the location block is:

location ~ \.php$ {
    try_files      $uri = 404;
    fastcgi_pass   php;
    fastcgi_index  index.php;
    include        fastcgi.conf;
}

that is: one should not specify the http:// protocol before referencing the php backend. The http://php syntax is to be used with the proxy_pass instruction, not fastcgi_pass.