Use more than one PHP version in Nginx

In some cases probably you need to have different PHP versions on the same machine and using it on different domains.

Install PHP

You can install PHP versions by downloading already compiled packages or you can compile your own (with personalized configuration – quick PHP compile & install guide).

Personally, I prefer for development machines to compile PHP by myself.  You can read how I prefer to install PHP in the linked article.

PHP FPM

In your “php-fpm” configuration file there is an option to specify the port used to listen:

; The address on which to accept FastCGI requests.
; Valid syntaxes are:
;   'ip.add.re.ss:port'    - to listen on a TCP socket to a specific address on
;                            a specific port;
;   'port'                 - to listen on a TCP socket to all addresses on a
;                            specific port;
;   '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = 127.0.0.1:9562

Nginx

The next step is to define the upstream in Nginx configuration, to be able to pass the requests to PHP.  Next, you will have a few examples:

# This will define upstream to local PHP-FPM server; for tools like 
upstream local-phpfpm {
	server   127.0.0.1:9053;
}
upstream phpfpm {
	#server unix:/var/run/php5-fpm.sock;
	server   127.0.0.1:9053;
}
upstream php53fpm {
	server   127.0.0.1:9053;
}
upstream php56fpm {
	server  127.0.0.1:9562;
}

Next time when you will configure a virtual host on your machine you will be able to use different PHP version on the same machine:

    location ~ .php$ { ## Execute PHP scripts
        fastcgi_pass    php53fpm;
        include        fastcgi_params; ## See /etc/nginx/fastcgi_params
    }


OR


    location ~ .php$ { ## Execute PHP scripts
        fastcgi_pass    php56fpm;
        include        fastcgi_params; ## See /etc/nginx/fastcgi_params
    }