Jeremy Morgan

My Blog about Programming, Tech, SEO, Marketing and whatever else I come up with.

How to Set Up a LEMP Server in Ubuntu 14.04

Today I’m going to show you how to set up a LEMP server (Linux NginX MariaDB PHP) on an Ubuntu 14.04. It’s a relatively easy process once you’ve done it a few times, but there are some things that can trip you up, so I thought I’d document it and present it here.

For this tutorial I used a Digital Ocean Droplet, but any Ubuntu 14.04 server should work the same way.

Set up a privileged user

This assumes you’re using a fresh install of Ubuntu 14.04, and it’s not a crucial step in the process if your server is already set up. But we want to create an environment with a privileged user and prevent people from being able to login as root over SSH. This is just an extra precaution I like to do on servers I set up.

Log in to your user as root, and type in the following:

1
adduser web

It doesn’t have to be “web” you can call it anything you want.

"How to set up a LEMP Server on Ubuntu 14.04"

Add a password and there will be some prompts where you can add as much or as little information as you want for the account.

Then run the following command:

1
visudo

look for

1
User privilege specification

and add the new account:

1
2
root    ALL=(ALL:ALL) ALL
web     ALL=(ALL:ALL) ALL

It should look like this:

"How to set up a LEMP Server on Ubuntu 14.04"

Ctrl + X to exit, Y to save the file

Now we want to edit the SSH settings:

1
sudo nano /etc/ssh/sshd_config

Change the Port to something between 1025 and 65536. This just adds an extra step for attackers, and bots that scan for open port 22 won’t find your connection immediately.

Look for this line:

1
PermitRootLogin yes

and change it to

1
PermitRootLogin no

This prevents people from logging into SSH as root.

As an additional step, let’s add the line:

1
AllowUsers web

so only the web user is allowed to log on to the server.

Restart the ssh server:

1
service ssh restart

Now before we log out, we want to test and make sure we can get back in.

1
ssh -p 4400 web@YourIPADDRESS

4400 is the port shown here, but it can be whatever you choose.

If you can log in fine, then you’ll be safe to exit out of your main session, and log back in as “web” (or whatever you used as a username).

Install the Web Server

first type in

1
sudo apt-get update

to update the system.

To install NginX:

1
sudo apt-get install nginx

In Ubuntu 14.04 it will automatically start up the service, and you should see this startup page:

"How to set up a LEMP Server on Ubuntu 14.04"

Now your NginX server is set up so we’ll move on and modify it later.

Install the Web Server

We’re going to install MySQL on the server, but we’ll be using the MariaDB fork instead of the MySQL distribution, because it’s better in many ways.

For our install we’re using Ubuntu 14.04 and I want MariaDB 10, so here is how I set it up:

1
2
3
sudo apt-get install software-properties-common
sudo apt-key adv --recv-keys --keyserver hkp://keyserver.ubuntu.com:80 0xcbcb082a1bb943db
sudo add-apt-repository 'deb http://sfo1.mirrors.digitalocean.com/mariadb/repo/10.0/ubuntu trusty main'

If you want to use something different or are working with a different OS, check here to see which repo to use.

1
2
sudo apt-get update
sudo apt-get install mariadb-server

Now we want to secure up our install a bit:

1
sudo mysql_secure_installation

enter your root password and answer “Y” to all the things you want to remove for security purposes.

Now you have a (MySQL compatible) MariaDB instance set up!

Install and configure PHP

Now we want to install PHP and get it set up with NginX.

1
sudo apt-get install php5-fpm php5-mysql php5-cli php5-mcrypt git

Now, we need to configure PHP:

1
sudo nano /etc/php5/fpm/php.ini

Look for the following in the php.ini file:

1
;cgi.fix_pathinfo=1

remove the semicolon and set it to 0:

1
cgi.fix_pathinfo=0

Quit and save the file.

Now we need to make a small change to the PHP-FPM config:

1
sudo nano /etc/php5/fpm/pool.d/www.conf

look for the listen directive and make sure it says:

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

Quit and save the file, then restart PHP5-FPM:

1
sudo service php5-fpm restart

Now you’re set up!

Configure NginX

Create a folder where your web files will be stored. I generally set up something like this:

1
sudo mkdir /var/www/yourdomain.com/public

Now open up this file:

1
sudo nano /etc/nginx/sites-available/default

The default server setup looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
server {
          listen 80 default_server;
          listen [::]:80 default_server ipv6only=on;

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

          server_name localhost;

          location / {
              try_files $uri $uri/ =404;
          }
      }

Make the following changes to the config so it looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
server {
          listen 80 default_server;
          listen [::]:80 default_server ipv6only=on;

          root /var/www/yourdomain.com/public;
          index index.php index.html index.htm;

          server_name server_domain_name_or_IP;

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

          error_page 404 /404.html;
          error_page 500 502 503 504 /50x.html;
          
          location = /50x.html {
              root /var/www/yourdomain.com/public;
          }

          # pass the PHP scripts to FastCGI server listening on /var/run/php5-fpm.sock
          location ~ \.php$ {
                try_files $uri /index.php =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;
          }
      }

Replace /var/www/yourdomain.com/public with whatever folder you’d like to use for your website (what you created earlier), and replace server_domain_name_or_IP with your server domain name or IP.

Now restart your web services:

1
2
sudo service php5-fpm restart
sudo service nginx restart

Now we can create a test file to check your PHP configuration:

1
nano /var/www/yourdomain.com/public/phpinfo.php

Add the following:

lang: php
1
<?php phpinfo();

Now bring up the page in a browser and you should see this:

"How to set up a LEMP Server on Ubuntu 14.04"

And you’re done!! Now you can add in your files and start building websites or applications. In future articles I’ll show some good deployment methods for your new website.

The Book Every PHP Developer Should Read

PHP has gotten a bad rap over the years. There is plenty of discussion around it’s “Fractal of Bad Design” and syntactical inconsistencies but the chief complaint is generally security. Lots of PHP sites get hacked by the minute, and even some experienced and knowledgeable programmers will say that the language is inherently insecure.

I have always argued against this because there is a common sense reason there are so many security breaches of PHP.

"PHP Security how to" PHP applications are hacked frequently because:

  1. There are so many PHP applications.
  2. It’s very easy to learn and write PHP.
  3. It’s easy to write bad PHP.

It’s that simple. PHP is popular and has been for many years. The more PHP out in the wild the more it will it’s exploited. Few of these hacks exploit flaws in the PHP processing engine itself, and are usually vulnerabilities of the scripts themselves.

This means, of course that it’s mostly the programmer’s fault when a PHP application is hacked. Sorry folks, but that’s the truth.

You can write PHP that’s just as secure (or more so) than other web languages out there. It’s time we started really striving towards that.

Your Best Defense against PHP Hacks

Writing secure PHP code is not a secret black art hidden away from PHP developers. But the information is so scattered it would take you weeks or months (or longer) to gather good PHP security practices into some sort of checklist or formula. Even then only true experience would tell you how much of it is true.

Thankfully Ben Edmunds has already done that for you. He recently released ”Building Secure PHP Apps - a Practical Guide” and it’s one of the best security related books I’ve ever read, and certainly the best covering PHP. In this review I’ll go over why I think every PHP developer should be reading this.

The book is a very concise guide that will bring to the next level as a developer and have you building better, more secure scripts.

Introduction

The book quickly jumps right in with a common sense rule about web development: Never Trust Your Users and Sanitize ALL Input. It starts by painting a small scenario and and jumps right into the technical ways that users can enter your system. In the first chapter it jumps right into topics like:

  • SQL Injection
  • Mass Assignable Fields
  • Typecasting
  • Sanitizing Input / Output

These are items that new PHP programmers (and some experienced ones) neglect all the time. Sanitizing input is seen as an optional step by many, and this chapter talks a lot about.

In reading it I was reminded of my first day on a job many years ago when I was digging into the existing code and found the following in the new user creation script:

1
2
3
if ($_POST["isadmin"] == 1) {
// code to set to admin in database 
}

I panicked when seeing this as it was a VERY active script and there was much to be gained by a malicious user who could have guessed this and inserted a simple form variable and accessed around 5,000 credit card numbers and other personal info.

Digging deeper I found stuff like:

1
$sql = "INSERT INTO database (id,name,...) VALUES (" . $_POST["Name"] . ");"

I almost walked out of that job on the first day because of this terrible stuff they were relying on. This stuff is out there and it’s up to you to change it, and definitely avoid creating more of it.

This chapter talks about why code like this is a terrible risk and how you can fix it.

HTTPS and Certificates

This is another area Ben covers with scenarios, stories and a little humor but also clearly explains some concepts of HTTPS that can be unclear. He explains it in a way that even your boss can understand it.

The book is very thorough in describing how certificates work, types of certificates and how they’re implemented, and even how to set them up in Apache or Nginx.

Passwords

In this book some careful explanation of passwords, hashes, lookup tables and salts is included that is incredibly helpful for developers creating a user login system.

Folks, this is one area that is extremely lacking even in 2014. I still run across applications that store plain text passwords or something silly like a ROT13 cipher to protect them. Please, for the sake of the people using your app and your good reputation don’t do this.

Passwords and other sensitive should be very difficult to obtain even if someone has full access to the database. This is covered pretty thoroughly here and will give you great direction for designing better systems.

Authentication and Access Control

The book covers this topic very thoroughly. When you’re building a new PHP application some of the first considerations are:

  • Who can access what resources?
  • Who can control other users access?

These are crucial things to think about for applications, especially ones handling sensitive data. A good portion of development in the enterprise world is devoted to this. If you set up authentication and access control improperly the best that can happen is you annoy your users and create more work. The worst than can happen is a severe data breach and / or data destruction.

In this book the basics are covered well, then it deep dives a little more into things like controlling access to files and individual pages of an application, and has plenty of code samples to look at.

Specific Exploits

The book covers some common exploits that are used to breach systems and goes into very good detail about Cross Site Scripting, arguably the most common way attackers exploit applications. It explains different types of attacks and how to protect yourself.

Sound Good? You can get this book at a discount using this link!

What I liked the most about this book

In reading this book I really enjoyed how information is presented in a way that’s useful for both beginners and experienced programmers. There is a set of concepts presented, what they are and how to protect yourself against it. There are plenty of code samples without “filler code” that some technical books suffer from.

You can go through this book fairly quickly because there isn’t a lot of fluff. Newer developers can go through this book and examine each topic and start looking at their code and making revisions to how they do things. Remember in this business you need to constantly change. If you look back and are ashamed of code you wrote 6 months ago you’re doing it right.

More advanced and experienced programmers can use this guide to fill in their weak spots (admit it no matter how long you’ve been in the game, you have them) and learn more about systems they’ve been using in their work. For instance I have used certificates like crazy over the years but never thought about things down to the level presented in this book.

No matter who you are, you’ll learn something. So stop reading this post and pick up a copy already! Use this link to purchase it for a discount!!

Disclaimer

I don’t do many reviews on my blog so you may have a few questions. To be clear, I am not being paid or compensated for this review. The coupon code above is to give my blog readers $4 off the price of the book, and I receive none of that. I did receive a promotional copy of the book for reviewing purposes of course.

Also I know the author personally and that’s one of the reasons I trust the information in this book and have full faith in it’s guidance. Ben Edmunds has been a huge influence in the PHP community over the years, he has over 10 years experience with PHP is one of the leaders of the Portland area PHP users group, and has made significant contributions to open source PHP projects over the years. It’s pretty safe to say he knows his stuff and you can trust the information presented here.

Create a Self Hosted API for Local Development

If you’ve ever worked in an overly restrictive environment, you know you have to come up with some workarounds to get your job done. I worked in such and environment and ran into a problem developing some front end pages to work with an API, but I didn’t want to use live data. Here’s a solution I came up with and I decided to write it out and explain it in hopes it will help others.

Properties vs Fields in C#

One of the areas that causes a lot of confusion for new C# developers is the idea of properties and fields. It’s an easy thing to mess up and there aren’t really any solid rules on it, but here are some general guidelines to help you decide how to use these members in your project.

Smell It Before You Eat It

Whether you’re developing for a personal project, small business or Fortune 100, you should take the time to make sure your changes aren’t going to break things. In times past this usually meant spending lots of money. These days the only thing you’ll need to spend for quality is time, and not much of it.

What Is Heartbleed?

On April 7th a security advisory was released titled “TLS heartbeat read overrun” (CVE-2014-0160) and it’s received a lot of attention in the IT community and the general public. Here’s a quick explanation of what Heartbleed is, and what it means for you.

How to Learn Computer Programming

So you want to be a computer programmer? Want to write software? Here is how you can get started with this awesome hobby / profession right away, for next to nothing. I first wrote this article back in 2008 and a lot has changed since then, so I decided to start it over completely.