How to install nginx with PHP & MySQL (LEMP) on Debian

What is Nginx?

nginx [engine x] is a free and open-source HTTP and reverse proxy server. It is also a mail proxy server.

This website ehosen.com is running on a Debian based VPS (Virtual Private Server). The HTTP server behind this website is Nginx.

In this article, you’ll learn how to install Nginx, PHP and MySQL on Debian Wheezy.

So let’s get started:

Installing nginx:

To install nginx, open up your terminal and type the following command:

apt-get install nginx

After getting this installed, we’ll need to start Nginx. To start Nginx, type the following command:

service nginx start

Type your server’s IP address on a browser. If everything is right, you should get a welcome message from Nginx.

The default root for nginx on debian wheezy is usr/share/nginx/www

Installing PHP5-FPM

Nginx is well known for serving static files, however, we can make this work with PHP5 through PHP-FPM (FastCGI Process Manager).

To install PHP5, type the following command on your terminal

apt-get install php5-fpm

Configuring nginx

To configure nginx to work with PHP-FPM we?ll need to open the default configuration file. To open the configuration file, type the following command on your terminal:

nano   /etc/nginx/sites-available/default

Now copy the following codes and paste on the opened file:

server {
  listen 80;

  root /var/www/example.com;
  index index.php;

  server_name example.com www.example.com;

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

  # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
  location ~ .php$ {
    try_files $uri = 404;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root $fastcgi_script_name;
    include fastcgi_params;
  }
}

Don’t forget to replace example.com with your actual domain name. For me, /var/www/example.com is the server root for my domain. Feel free to change it, if yours is different!

Now restart nginx with the following command:

service nginx restart

Now open php.ini file with the following command:

nano /etc/php5/fpm/php.ini

Find the following line this line and set:

cgi.fix_pathinfo=0

Restart PHP5-FPM with the following command:

service php5-fpm restart

Create a file on your servers root directory called test.php with the following command:

nano /var/www/example.com/test.php

Put the following code on it:

<?php

phpinfo();

?>

Save the file.

Now type your domain name with the path of the test file on your browser like:

example.com/test.php

If you’ve done everything correctly, you should see the following page:

Installing MySQL

To install MySQL type the following command on your terminal:

apt-get install mysql-server mysql-client

Now start MySQL with this command:

service mysql start

Now, you’re successfully running your Linux (Debian Distro), Nginx (Engine X), MySQL, and PHP (LEMP) server.

Cheers!