Installing Nginx With PHP5 (And PHP-FPM) And MySQL Support (LEMP) On Ubuntu 12.04 LTS

Want to support HowtoForge? Become a subscriber!
 
Submitted by falko (Contact Author) (Forums) on Tue, 2012-05-22 17:36. :: Ubuntu | Web Server | nginx

Installing Nginx With PHP5 (And PHP-FPM) And MySQL Support (LEMP) On Ubuntu 12.04 LTS

Version 1.0
Author: Falko Timme <ft [at] falkotimme [dot] com>
Follow me on Twitter
Last edited 05/02/2012

Nginx (pronounced "engine x") is a free, open-source, high-performance HTTP server. Nginx is known for its stability, rich feature set, simple configuration, and low resource consumption. This tutorial shows how you can install Nginx on an Ubuntu 12.04 LTS server with PHP5 support (through PHP-FPM) and MySQL support (LEMP = Linux + nginx (pronounced "engine x") + MySQL + PHP).

I do not issue any guarantee that this will work for you!

 

1 Preliminary Note

In this tutorial I use the hostname server1.example.com with the IP address 192.168.0.100. These settings might differ for you, so you have to replace them where appropriate.

I'm running all the steps in this tutorial with root privileges, so make sure you're logged in as root:

sudo su

 

2 Installing MySQL 5

In order to install MySQL, we run

apt-get install mysql-server mysql-client

You will be asked to provide a password for the MySQL root user - this password is valid for the user root@localhost as well as root@server1.example.com, so we don't have to specify a MySQL root password manually later on:

New password for the MySQL "root" user: <-- yourrootsqlpassword
Repeat password for the MySQL "root" user: <-- yourrootsqlpassword

 

3 Installing Nginx

Nginx is available as a package for Ubuntu 12.04 which we can install as follows:

apt-get install nginx

Start nginx afterwards:

/etc/init.d/nginx start

Type in your web server's IP address or hostname into a browser (e.g. http://192.168.0.100), and you should see the following page:

The default nginx document root on Ubuntu 12.04 is /usr/share/nginx/www.

 

4 Installing PHP5

We can make PHP5 work in nginx through PHP-FPM (PHP-FPM (FastCGI Process Manager) is an alternative PHP FastCGI implementation with some additional features useful for sites of any size, especially busier sites) which we install as follows:

apt-get install php5-fpm

PHP-FPM is a daemon process (with the init script /etc/init.d/php5-fpm) that runs a FastCGI server on port 9000.

 

5 Configuring nginx

The nginx configuration is in /etc/nginx/nginx.conf which we open now:

vi /etc/nginx/nginx.conf

The configuration is easy to understand (you can learn more about it here: http://wiki.nginx.org/NginxFullExample and here: http://wiki.nginx.org/NginxFullExample2)

First (this is optional) adjust the number of worker processes and set the keepalive_timeout to a reasonable value:

[...]
worker_processes  4;
[...]
    keepalive_timeout   2;
[...]

The virtual hosts are defined in server {} containers. The default vhost is defined in the file /etc/nginx/sites-available/default - let's modify it as follows:

vi /etc/nginx/sites-available/default

[...]
server {
        listen   80; ## listen for ipv4; this line is default and implied
        listen   [::]:80 default ipv6only=on; ## listen for ipv6

        root /usr/share/nginx/www;
        index index.php index.html index.htm;

        # Make site accessible from http://localhost/
        server_name _;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to index.html
                try_files $uri $uri/ /index.html;
                # Uncomment to enable naxsi on this location
                # include /etc/nginx/naxsi.rules
        }

        location /doc/ {
                alias /usr/share/doc/;
                autoindex on;
                allow 127.0.0.1;
                deny all;
        }

        # Only for nginx-naxsi : process denied requests
        #location /RequestDenied {
                # For example, return an error code
                #return 418;
        #}

        #error_page 404 /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
                root /usr/share/nginx/www;
        }

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ \.php$ {
                try_files $uri =404;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                include fastcgi_params;
        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        location ~ /\.ht {
                deny all;
        }
}
[...]

Uncomment both listen lines to make nginx listen on port 80 IPv4 and IPv6.

server_name _; makes this a default catchall vhost (of course, you can as well specify a hostname here like www.example.com).

I've added index.php to the index line. root /usr/share/nginx/www; means that the document root is the directory /usr/share/nginx/www.

The important part for PHP is the location ~ \.php$ {} stanza. Uncomment it to enable it. Please note that I've added the line try_files $uri =404; to prevent zero-day exploits (see http://wiki.nginx.org/Pitfalls#Passing_Uncontrolled_Requests_to_PHP and http://forum.nginx.org/read.php?2,88845,page=3). Alternatively, if you don't want to use the try_files $uri =404; line, you can set cgi.fix_pathinfo = 0; in /etc/php5/fpm/php.ini (don't forget to reload PHP-FPM afterwards).

Now save the file and reload nginx:

/etc/init.d/nginx reload

Now create the following PHP file in the document root /usr/share/nginx/www:

vi /usr/share/nginx/www/info.php

<?php
phpinfo();
?>

Now we call that file in a browser (e.g. http://192.168.0.100/info.php):

As you see, PHP5 is working, and it's working through FPM/FastCGI, as shown in the Server API line. If you scroll further down, you will see all modules that are already enabled in PHP5. MySQL is not listed there which means we don't have MySQL support in PHP5 yet.

 

6 Getting MySQL Support In PHP5

To get MySQL support in PHP, we can install the php5-mysql package. It's a good idea to install some other PHP5 modules as well as you might need them for your applications. You can search for available PHP5 modules like this:

apt-cache search php5

Pick the ones you need and install them like this:

apt-get install php5-mysql php5-curl php5-gd php5-intl php-pear php5-imagick php5-imap php5-mcrypt php5-memcache php5-ming php5-ps php5-pspell php5-recode php5-snmp php5-sqlite php5-tidy php5-xmlrpc php5-xsl

Xcache is a free and open PHP opcode cacher for caching and optimizing PHP intermediate code. It's similar to other PHP opcode cachers, such as eAccelerator and APC. It is strongly recommended to have one of these installed to speed up your PHP page.

Xcache can be installed as follows:

apt-get install php5-xcache

Now reload PHP-FPM:

/etc/init.d/php5-fpm reload

Now reload http://192.168.0.100/info.php in your browser and scroll down to the modules section again. You should now find lots of new modules there, including the MySQL module:

 

7 Making PHP-FPM Use A Unix Socket

By default PHP-FPM is listening on port 9000 on 127.0.0.1. It is also possible to make PHP-FPM use a Unix socket which avoids the TCP overhead. To do this, open /etc/php5/fpm/pool.d/www.conf...

vi /etc/php5/fpm/pool.d/www.conf

... and make the listen line look as follows:

[...]
;listen = 127.0.0.1:9000
listen = /tmp/php5-fpm.sock
[...]

Then reload PHP-FPM:

/etc/init.d/php5-fpm reload

Next go through your nginx configuration and all your vhosts and change the line fastcgi_pass 127.0.0.1:9000; to fastcgi_pass unix:/tmp/php5-fpm.sock;, e.g. like this:

vi /etc/nginx/sites-available/default

[...]
        location ~ \.php$ {
                try_files $uri =404;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass unix:/tmp/php5-fpm.sock;
                fastcgi_index index.php;
                include fastcgi_params;
        }
[...]

Finally reload nginx:

/etc/init.d/nginx reload

 

8 CGI/Perl Scripts

If you want to serve CGI/Perl scripts with nginx, please read this tutorial: Serving CGI Scripts With Nginx On Debian Squeeze/Ubuntu 11.04

The recommended way is to use fcgiwrap (chapter 4).

 

9 Links

 

About The Author

Falko Timme is the owner of nginx WebhostingTimme Hosting (ultra-fast nginx web hosting). He is the lead maintainer of HowtoForge (since 2005) and one of the core developers of ISPConfig (since 2000). He has also contributed to the O'Reilly book "Linux System Administration".


Please do not use the comment function to ask for help! If you need help, please use our forum.
Comments will be published after administrator approval.
Submitted by Josh (not registered) on Fri, 2013-11-01 08:47.
This is over a year old but I really found it helpful. On step 7 I found I had to restart php5-fpm in order to hit any of my test pages from the previous steps. Just a heads up if you made it that far :) 
Submitted by Manohar Negi (not registered) on Sun, 2013-10-20 10:34.

After searching a lot, I found you page. This is really informative and it helped me to great extent.

Submitted by Vance (not registered) on Mon, 2013-10-14 14:36.

Hi Timmen, 

 Really nice article. I ran across a few small issues while setting this up and so documented and wrote a guide on it as well. Just small things like removing apache first, installing phpmyadmin as part of the install, and a slightly different server container config as I had a small issue using the one here while using TCP/IP.

 I'll leave a link here for those that might run into small issues and need a fix for them. I am also making a video just to further clarify.

http://portal.ioflare.com/knowledgebase/4/Installing-LEMP-Stack-On-Your-Ubuntu-Cloud-Server.html

Submitted by jeb bushell (not registered) on Wed, 2013-07-24 11:52.

If you merge steps 5 and 7 before attempting to view info.php you may avoid the 502 bad gateway error that I got, even after I'd taken into account the above comments.    After all, if your server spec is out of line with www.conf  then you might reasonably expect trouble.  Step 6 is next.

Submitted by Ryan (not registered) on Wed, 2013-07-17 07:57.
I get nginx 404 using codeigniter.
Submitted by Vijay (not registered) on Wed, 2013-07-10 22:51.
This line didn't work for me:

listen = /tmp/php5-fpm.sock 

I had to use:

listen = /var/run/php5-fpm.sock 

 

I also didn't need to modify:

 /etc/nginx/sites-available/default

Submitted by Fouwaaz (not registered) on Mon, 2013-05-20 18:58.

Thank you for this great article. 

I faced an issue in Step # 7 though.  After reloading php I got a 502 Bad Gateway.  The fastcgi_pass in step # 5 had to be changed to /tmp/php5-fpm.sock.  Originally there were 2 lines of fastcgi_pass and I had to comment out one.

 

Submitted by Chris P (not registered) on Thu, 2013-05-02 00:08.
Just a note: 
 

The latest distribution of PHP5-fpm came pre-configured to run on a socket first. I think most will notice this too. But the default socket for me, just in case anyone needs to know, was...

/var/run/php5-fpm.sock

 I don't know if you want to update this article since people will find out anyways.

Submitted by Haneef (not registered) on Sat, 2012-10-20 23:09.

I have been using windows in my development and when configuring a server on linux, it has been apache2.  I decided to use nginx for the speed it provides (and it's asynchronous nature) but was struggling to configure it (with PHP) and every article I found online was just messing up my install.  Then I came across your article and things worked like a dream!  Your configuration is simple, your tutorial steps are to the point.  I wish I stumbled upon this article sooner!

Thank you for de-mystifying the waters!

Submitted by Lawrence Taur (not registered) on Sat, 2012-06-16 11:51.
I've followed the steps mentioned above but i get stuck when i try to load php.info

i get stuck after creating vi /usr/share/nginx/www/info.php 

even though info.php exists in the /usr/share/nginx/www folder, the browser returns a 404 not found error.

can someone help me here.  

Submitted by cantor (not registered) on Wed, 2012-08-15 12:05.

I had the same issue.  It seems to work with:
fastcgi_pass unix:/tmp/php5-fpm.sock;
instead of
fastcgi_pass unix:/var/run/php5-fpm.sock;

for example:

location ~ \.php$ {
                try_files $uri =404;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass unix:/tmp/php5-fpm.sock;
                fastcgi_index index.php;
                include fastcgi_params;
        }
 

Hope that helps.

Submitted by Sergio (not registered) on Tue, 2012-05-22 20:33.

Thanks a lot for the tutorial on how to install ngnix with PHP5 support on Ubuntu. However I see here the same problem that I see in all PHP5 installations using FastCGI on nginx and that is:

 

location ~ \.php$

 

This line tells nginx to pass the request over to the php-cgi process when the request ends with .php but what about PHP scripts that doesn't end in PHP, like CodeIgniter URLs:

 

example.com/index.php/shoes/display/23

 

This will cause an error. A way to fix this is to change the regular expression for this one:

 

location ~ \.php

 

But this is not very safe because it causes the php-cgi process to try and run any file which contains .php anywhere on it's name for example an image called

tutorial.php-mysql.jpg

Will be passed as a script file to the php-cgi process. In that case it will cause an error but this can also give an attacker a way to execute malicious code at will.

So, have anyone found any way to solve this issue?

Submitted by Daniel15 (registered user) on Tue, 2012-06-12 04:41.
Take a look at the CodeIgniter article on the Nginx wiki and how its configuration handles it using the try_files setting.
Submitted by falko (registered user) on Wed, 2012-05-23 07:57.

I haven't tried this, but I guess

location ~ ^(.+\.php)(/.+)$ {
                try_files $uri =404;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                include fastcgi_params;
}

could work. What do you think?

Submitted by Daniel15 (registered user) on Tue, 2012-06-12 04:45.

The best way to do it is to have a block like this:

location / {
try_files $uri $uri/ /index.php;
}

This will check if the requested file exists, and if not, perform an internal rewrite to index.php. Then the index.php FastCGI rule will always match (and 404s will be routed via your PHP app). 

See:
http://wiki.nginx.org/Codeigniter
http://wiki.nginx.org/Pitfalls#Front_Controller_Pattern_based_packages

Submitted by Anonymous (not registered) on Mon, 2012-12-17 11:40.
 It's worth having a read of this:

https://nealpoole.com/blog/2011/04/setting-up-php-fastcgi-and-nginx-dont-trust-the-tutorials-check-your-configuration/

This tut has vulnerable configs (not that its easy to prevent when using this method).