Installing and Configuring Nginx Web Server with PHP and MySQL

If you want your cloud server to be provide access to your websites via the Internet, you will need to install a bit of 'web server' software.

There are a few different options available to you in this regard, but the two main web server applications we have used are:

  • Apache Web Server
  • nginx

As we run our websites using PHP code and therefore require PHP to dynamically generate pages, our web server will need to have a tie in with PHP software.

In Apache you have a PHP module built-in, which unfortunately loads a new PHP instance to memory with every request, whether the request is for a static file or PHP. This makes it a more memory intensive web server.

With nginx you have a php cgi (common gateway interface) - this delegates the decoding and execution of PHP coded scripts to a seperate process. This keeps the memory footprint of the server low as well as serving up static files whilst using much lower system resources.

We will install nginx along with the PHP-FPM (FastCGI Process Manager). Let's get started.

Install nginx as below:

# sudo apt-get update
# sudo apt-get install nginx

Run it:

# sudo service nginx start

Next, we install PHP, along with various modules - including the FPM module.

# sudo apt-get install php5-cgi php5-mysql php5-curl php5-gd php5-idn php-pear php5-imagick 
php5-imap php5-mcrypt php5-memcache php5-mhash php5-ming php5-pspell php5-recode 
php5-snmp php5-sqlite php5-tidy php5-xmlrpc php5-xsl

When done, run the following also:

# sudo aptitude update

# sudo aptitude install php5-fpm

# sudo service php5-fpm start

PHP and PHP-FPM are now also installed. All that is required now to allow you cloud slice to serve webpages is to configure Nginx.

Nginx will be installed as default to run under the user 'www-data'. We need to make sure that the 'www-data' user is within the same user group as the user you access the server under e.g. 'mynewusername':

# sudo usermod -a -G www-data mynewusername

We will store all of our web 'stuff' inside the /var/www folder structure, so we need to change the ownership of that folder (and folders within it) to the 'www-data' user - so that the web server has access to it:

# sudo chown -R www-data:www-data /var/www

Give 775 permissions to the folder (and folders within it) :

# sudo chmod -R 775 /var/www

Now, you need to create your website structure within the /var/www/ folder, so let's assume your website will be 'mywebsite.com'. Create the directory structure for this website, so that you have public and logs folders within it :

# mkdir -p /var/www/mywebsite.com/{public,logs}

Great! We now have a directory created where we can put webpages etc for our website. All we need to do now if create a virtual host file - this file is what links the directory structure to a specific website. By this principle you can have many directory structures and virtual host files and therefore serve many different websites on one cloud server.

Create a virtual host file in the /etc/nginx/sites-available/ folder:

# sudo nano /etc/nginx/sites-available/mywebsite.com

Type the following in this file:


server {
     listen   80;
     server_name mywebsite.com;

     access_log /var/www/mywebsite.com/logs/access.log;
     error_log /var/www/mywebsite.com/logs/error.log;

     location / {
          root   /var/www/mywebsite.com/public/;
          index  index.html index.php index.htm;
          }


        #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   /var/www/nginx-default;
        }


        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
                #proxy_pass   http://127.0.0.1;
        #}                                           

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ \.php$ {
                fastcgi_pass   127.0.0.1:9000;
                fastcgi_index  index.php;
                fastcgi_param  SCRIPT_FILENAME  /var/www/mywebsite.com/public$fastcgi_script_name;
                include        /etc/nginx/fastcgi_params;
        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one

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


}

The virtalhost configuration above creates a server listening on port 80 at requests for the domain mywebsite.com, saves access attempts to the 'access_log' path, and errors to the 'error_log' path. For all requests from the home directory, it sets the root directory on the file system and explicity states the filename to look for as default, if one isn't supplied.

It is set up to pass all php file requests to the PHP-FPM to handle.

Now to test your nginx server setup, do the following: (i'm going by the virtualhost config above)

  • Go to your websites home directory:

    # cd /var/www/mywebsite.com/public/
    
  • Create a new file with the nano editor by running the following:

    # nano index.php
    
  • This will bring up the nano editor, type the following in it:

    <?php  phpinfo();  ?>
    

    Save and exit the file by hitting CTRL+X and entering Y

You have so far installed nginx, php including the php-fpm module, created a directory structure on your cloud slice for your website domain and it's files, created a nginx virtualhost file and created a test php file in your domain root directory containing a small piece of php code to bring up the full configuration details in your web browser.

To make your virtualhost file active you have to enable it.

You will remember that you created the 'mywebsite.com' virtualhost file in the '/etc/nginx/sites-available/' folder.

To enable it, you need to create a shortcut/symlink for the file to the '/etc/nginx/sites-enabled/' folder.

Anything in that folder will be scanned on every http request.

To create a symlink do the following:

# sudo ln -s /etc/nginx/sites-available/mywebsite.com   /etc/nginx/sites-enabled/mywebsite.com

Then restart the nginx server:

# sudo service nginx restart

If all went well, it should restart without errors.

If you dns is all set up correctly, you can navigate to mywebsite.com on your own computer's web browser and should see the PHP Information Page, showing you the configuration details.

Great! Before we finish, let's quickly install mysql and associated modules.

Run the following:

# sudo apt-get install mysql-server php5-mysql mysql-client

That's it. You can create databases as required below:


# mysql -u root -p
Enter password:   <---- you would enter your login password here

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 162
Server version: 5.1.41-3ubuntu12.6 (Ubuntu)

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> create database testdb;
Query OK, 1 row affected (0.00 sec)
mysql> grant all on testdb.* to 'dbuser1' identified by 'db_user_pw';
Query OK, 0 rows affected (0.00 sec)
mysql> quit
Bye

To complete, restart your PHP-FPM service and your nginx server :

# sudo service php5-fpm restart
# sudo service nginx restart

Category: cloud server

Tags: apache mysql nginx php

0 comments

Login or Register to post comments.

My Work!

Value My Car Android app logo

Value My Car Android app

Value any car for free - all makes and models available.

Get a free valuation of any car based on car depreciation trends for the specific make and model, the price you paid, your length of ownership and mileage covered. You can find out how much a car purchased at any point during its life-cycle will continue to depreciate.

view app
Value My Car iOS app logo

Value My Car iOS app

Value any car for free - all makes and models available.

Get a free valuation of any car based on car depreciation trends for the specific make and model, the price you paid, your length of ownership and mileage covered. You can find out how much a car purchased at any point during its life-cycle will continue to depreciate.

view app
NiceAreas.co.uk Website logo

NiceAreas.co.uk Website

Search For UK Areas Based on any Criteria

A number of tools to help research parts of the UK down to postcode sector level using multiple datasets and a variety of data combination and aggregation.

Including crime, house prices, travel links, jobs and more!

visit website
Mortgage Calculator Expert iOS app logo

Mortgage Calculator Expert iOS app

This comprehensive mortgage calculator includes eight different calculators in one app!

Adjust repayment types, rate types, initial offers/periods, base rates, terms, SVR's, overpayments, collars/caps, any fees (add to loan or upfront), mortgage start dates, simulated rate changes and more!

view app
Mortgage Calculator Expert Android app logo

Mortgage Calculator Expert Android app

This comprehensive mortgage calculator includes eight different calculators in one app!

Adjust repayment types, rate types, initial offers/periods, base rates, terms, SVR's, overpayments, collars/caps, any fees (add to loan or upfront), mortgage start dates, simulated rate changes and more!

view app
Amazon Alexa Skills logo

Amazon Alexa Skills

Multiple Alexa Skills

Voice-first (with additional display elements too) skills for Alexa devices.

Including:

BrainPickers! Guess The ... series of games.

SalaryBee - Salary calculations by voice.

TheMoneyCalculator - Finance calculations by voice.

NiceAreas - Property valuations, Area information and census information by voice.

Who Said That? Friends Quiz.

..plus...more to come!

visit website
UKTaxCalculators.co.uk iOS app logo

UKTaxCalculators.co.uk iOS app

The UK's most comprehensive FREE tax calculator app

The website condensed into a full featured and easy to use iPhone/iPad/iPod app!

Check tax on any income source, compare salaries and much more!

view app
UKTaxCalculators.co.uk Android app logo

UKTaxCalculators.co.uk Android app

The UK's most comprehensive FREE tax calculator app

The website condensed into a full featured and easy to use Android app!

Check tax on any income source, compare salaries and much more!

view app
UKTaxCalculators.co.uk Amazon app logo

UKTaxCalculators.co.uk Amazon app

The UK's most comprehensive FREE tax calculator app

The website condensed into a full featured and easy to use Amazon app!

Check tax on any income source, compare salaries and much more!

view app
UK Tax Pro iOS app logo

UK Tax Pro iOS app

Calculate UK Tax on any income type with single or multiple income sources.

Get a full breakdown of your tax, print/email from within the app.

Full compliment of professional features such as rates and allowances, news, guides and calendars.

view app
Parcel Dogs Game For iOS logo

Parcel Dogs Game For iOS

This 'top-down' racing game involves the player taking the role of Jim, our Speedy Parcel delivery dog. Now Jim has to go around his picking up parcels with the help of his map but has a hard time of it thanks to his nemesis Crazy Dave.
visit website
UKTaxCalculators.co.uk Website logo

UKTaxCalculators.co.uk Website

The UK's most comprehensive FREE online tax calculator suite

The Tax Calculator provides a full breakdown of tax for PAYE, CIS or Self Employed individuals providing options for Pension Calculations, Tax Codes, NIC Letters, Bonuses, Salary Sacrifice Schemes and more.

For people with multiple income sources, the UK Tax Calculators Wizard calculates every UK tax across all incomes in the same manner a tax return would.

visit website
Walleto.co.uk Website logo

Walleto.co.uk Website

The first truly easy to use, free online budget planner

There has never been an easier way to forecast your finances in less 5 minutes!

The budget calculator takes all your income details, across any type of income, calculates the taxes due, subtracts your expenses (both from extensive presets to your own defined expenses). You are presented with an online forecast, comparisons with other users with similar households as well as a printable report version to use as income and expenses chart.

visit website
TheMoneyCalculator.com Website logo

TheMoneyCalculator.com Website

Full featured online mortgage and loan calculators

You can use this website to calculate mortgage payments, forecast future interest rate effects, calculate remaining balances, check debt consolidation options, plan your savings, plan your pension as well as plan for your future house purchase. A lot of planning made easy!

Find a professional mortgage adviser or financial adviser online through our UK-wide network.

visit website
WhereDidMyTaxGo.co.uk Website logo

WhereDidMyTaxGo.co.uk Website

Ever wanted to know where the UK Government has been spending YOUR tax payments?

The WhereDidMyTaxGo.co.uk website takes your gross income since 2003, calculates your taxes (PAYE only), and uses the Governments expenditure data to give you an approximation of how much of your actual payments were spent where.

The personalised aspect of this website is a unique use of Government data.

visit website
TaxPenny.co.uk Website logo

TaxPenny.co.uk Website

Finding an Accountant the Smart Way

TaxPenny provide an online platform for accountants and those seeking an accountant to connect. Potential clients describe their circumstances, the work required and set a maximum price rage. Quotes are returned to clients within 1 working day. Accountants are able to search for new clients through various criteria and bid auction style for leads or purchase adhoc.

visit website
World Tax Calculator iOS app logo

World Tax Calculator iOS app

Compare Tax and Cost of Living of Major Economies

Calculate and/or compare taxes for major economies across the world, see differences in take home pay and see a cost of living comparison with a list of common purchases people make.

view app
World Tax Calc Android app logo

World Tax Calc Android app

Compare Tax and Cost of Living of Major Economies

Calculate and/or compare taxes for major economies across the world, see differences in take home pay and see a cost of living comparison with a list of common purchases people make.

view app

My Blog!

27/01/15 19:37:10

Using Cloud-based Load Balancing To Horizontally Scale Effectively

In this quick guide, we will go through what is required to convert an existing singular LAMP setup to a horizontally distributed network of servers sitting behind a Load Balancer. This guide will utilise a number of services from Rackspace Cloud.

cloud server

0

19/12/14 11:13:49

Creating Servers For Load Balancing

In this step-by-step guide we create the underlying server structure required for successful load balancing.

cloud server

0

14/09/14 14:40:59

Creating a Shared Memcached Cloud Instance

Key-value memory based storage can be a significant performance boost, as well as load reducer, for database heavy websites. Follow our step-by-step guide to setting one up using the Memcached application.

cloud server

0

27/06/14 12:12:01

Copying Data Across From Existing MySQL Databases to a Cloud Database

Now that you have created a database in the cloud, how do you get it populated as quickly as possible. Follow our step-by-step guide.

cloud server

0

27/03/14 13:14:05

Converting a Single Node MySQL Application to a Cloud Databases Instance

Switching from an existing single database application to a database in the cloud requires two steps. First is to actually create the cloud database instance. The second is to migrate your existing data across. We describe the steps required.

cloud server

0

.. or read all of my blog!

Get in touch!

Do you have any questions for me? An idea for an exciting new website or mobile application? Maybe you just want to leave a comment regarding one of my websites or apps? If yes then you've found the right place!

Complete the form below and I will get back to you as soon as possible. If you would prefer to get in touch via Twitter, you can reach me there using @rayarmanappdev.