Install PHP 5.4 and Nginx on Ubuntu 12.04

Posted by Andrew McCombe on Wed Feb 13, 2013

Summary: How to install PHP 5.4 and Nginx on Ubuntu 12.04 Server

Over the years Apache has been the undisputed king of the web-server market and has formed an integral part of the LAMP (Linux, Apache, MySQL and PHP) stack. Recently however, new kid on the block Nginx has undertaken massive growth whilst Apache’s share has been waning, according to Netcraft’s February 2013 survey. Whilst the LAMP stack is easy to install (sudo tasksel & select ‘LAMP’), installing PHP 5.4 and Nginx on Ubuntu 12.04 isn’t as straightforward. For a start, the packaged Nginx is out of date and PHP5.4 isn’t currently available at all out of the box. Luckily there are PPA’s for installing PHP 5.4 and Nginx.

Install Nginx

To install Nginx you will need to add the following PPA. Open a terminal and run the following commands:

Once this is installed Nginx should be running. To prove this, visit http://localhost and you should see the default Nginx screen:

Nginx default screen

Nginx default screen

If you don’t see this Nginx may not have been started. Simple run the following command and try http://localhost again:

Congratulations! You’ve successfully install Nginx on Ubuntu.

Install PHP 5.4

You should NOT install the default Ubuntu PHP packages as these will install PHP 5.3.10. There’s nothing wrong with 5.3.x but the newer 5.4 is much improved and is faster (up to 50% faster in some cases!)

Instead of the default packages you can install PHP5.4 from a PPA. On your terminal, run the following commands:

Once installed you need to configure Nginx to serve PHP pages. Using your terminal:

Scroll down to the PHP section (Around line 80) and change it to look like the following. You shouldn’t need to add anything, just uncomment some lines:

Once you have done that, save the file and restart both the php-fpm service and nginx:

Now create the following PHP script:

Save the file and open http://localhost/info.php. You should see the PHP Info page detailing your PHP version and a list of all modules currently loaded.

PHPinfo served by Nginx

PHPinfo served by Nginx

502 Bad Gateway Error

When I first installed Nginx and PHP5.4 I encountered a ‘502 Bad Gateway’ error from Nginx. It turns out that I hadn’t started the php5-fpm service so if you come across this, try restarting it with: