How to install Nginx Webserver with ssl

How to install Nginx Webserver with ssl

by -
0 1062


Nginx pronounced engine-x is a free, open-source, high-performance HTTP server and reverse proxy, as well as an IMAP/POP3 proxy server. Igor Sysoev started development of Nginx in 2002, with the first public release in 2004. Nginx now hosts nearly.12.18% (22.2M)of active sites across all domains. Nginx is known for its high performance, stability, rich feature set, simple configuration, and low resource consumption.Nginx is one of a handful of servers written to address the C10K problem .Unlike traditional servers, Nginx doesn’t rely on threads to handle requests. Instead it uses a much more scalable event-driven (asynchronous) architecture. This architecture uses small, but more importantly, predictable amounts of memory under load.

Even if you don’t expect to handle thousands of simultaneous requests, you can still benefit from Nginx’s high-performance and small memory footprint. Nginx scales in all directions: from the smallest VPS all the way up to clusters of servers.

Nginx powers several high-visibility sites, such asNetflix, Hulu, Pinterest, CloudFlare, Airbnb,, GitHub, SoundCloud, Zynga, Eventbrite, Zappos, Media Temple, Heroku, RightScale, Engine Yard and MaxCDN .

LEMP stack

LEMP stack is nothing but a group of open source softwares combined together to make a webserver.  LEMP refers to the first letters of Linux , Nginx ( Engine x ) , Mysql and PHP .

About Nginx, It is a lightweight webserver which is more stable and secure, it serves static content 50 times faster than Apache.



1. OS as any Linux flavour, Here we are using Centos 6.x.

2. Required RAM.

Install LEMP on centos 6.6

Let’s start the installation .
Nginx installation

Step 1 » Install Nginx repository package . you could find the latest package here.
Please follow all the steps as per given for installation of nginx.
First of all ,we will download and install nginx repo .

# rpm -ivh


You can also first download the packages, and then intsall using rpm command.

Create a file /etc/yum.repos.d/nginx.repo and add the following lines to the file.

For this you should know that all the packages ,which we install are either placed in repos or install with the help of related repositories in linux.

You can look at path , /etc/yum.repos.d.

I m giving you snapshot and view of all repos in linux.
Just look at all the repos and then nginx.repo, which we have just installed above , which comes here at this path.

Note:For future , there will be one lecture , video and detailed description for regarding yum , its repos and related to co.


# vi nginx.repo


# nginx.repo


name=nginx repo


Step 2: Update the repository and install nginx.

[root@nginxserver ~]#yum check-update
[root@nginxserver ~]#yum install nginx -y

Step 3 » After the installation . Let’s start the service .

[root@nginxserver ~]#service nginx start

Issue the below command to start service automatically while reboot.
[root@nginxserver ~]#chkconfig nginx on

Step 4: These are the default directories and files

Default document root directory: /usr/share/nginx/html
Default configuration file: /etc/nginx/nginx.conf
Default Virtual host config directory: /etc/nginx/conf.d/
Default Virtual host config file: /etc/nginx/conf.d/default.conf

Step 5» Now the nginx service has started

Check the listening 80 port using netstat command

[root@nginxserver ~]# netstat -ntlp | grep 80

tcp 0 0* LISTEN 1087/nginx


Step 6: If you are using firewall, then you have allow 80 port by iptables rule.

Now open /etc/sysconfig/iptables file and add the following line.
-A INPUT -p tcp --dport 80 -j ACCEPT

Which should be before reject line looks below
-A INPUT -i lo -j ACCEPT
-A INPUT –p tcp –dport 80 -j ACCEPT
-A INPUT tcp -p tcp --dport 22 -j ACCEPT

and restart iptables service
[root@nginxserver ~]# service iptables restart

Step 7» Now open your browser and goto http://serverip ( you could see the default nginx page like below.



Mysql installation

Step 8 » Install mysql server and client using the below command.
[root@nginxserver ~]# yum install mysql mysql-server -y

Step 9 » Start mysql service and enable automatic start during bootup.
[root@nginxserver ~]# service mysqld start
[root@nginxserver~]#chkconfig mysqld on

Step 10 » Use below command to secure mysql installation and for creating root password. This will prompt to enter current password, just press enter and create a new password and proceed the installation by giving yes to all.
[root@nginxserver ~]# /usr/bin/mysql_secure_installation


In order to log into MySQL to secure it, we'll need the current

password for the root user. If you've just installed MySQL, and

you haven't set the root password yet, the password will be blank,

so you should just press enter here.

Enter current password for root (enter for none):

OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MySQL

root user without the proper authorisation.

Set root password? [Y/n] y

New password:

Re-enter new password:

Password updated successfully!

Reloading privilege tables..

... Success!

Step 11 » Test your mysql connection using the created password.

[root@nginxserver ~]# mysql -u root -p

Enter password:

Welcome to the MySQL monitor. Commands end with ; or \g.

Your MySQL connection id is 10

Server version: 5.1.73 Source distribution

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective


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



PHP installation

PHP-FPM is an alternative PHP FastCGI implementation .
Step 12 » Install php-fpm and php-mysql.

Step 13 » Open /etc/php-fpm.d/www.conf which is config file for php-fpm and change user and group from apache to nginx.

; Unix user/group of processes

; Note: The user is mandatory. If the group is not set, the default user’s group

; will be used.

; RPM: apache Choosed to be able to access some dir as httpd

user = nginx

; RPM: Keep a group allowed to write in log dir.

group = nginx



Step 14 » Start php-fpm service and enable auto start during startup.

[root@nginxserver ~]# service php-fpm start

Starting php-fpm: [ OK ]

[root@nginxserver ~]# chkconfig php-fpm on

Step 15 » Create a virtual host /etc/nginx/conf.d/phptest.conf file and add the below code .

server {
listen 8080; # listen port
server_name; # Server name
location / {
root /usr/share/nginx/html; # Document root
index index.php index.html index.htm;
location ~ \.php$ {
root /usr/share/nginx/html; # Document root
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;

Step 16 » Create info.php in the path /usr/share/nginx/html

Create info.php in the path /usr/share/nginx/html as mentioned in the Vhost config file and add the below lines .you can see that the document root in above file, it is the path where we will put above website files.


root /usr/share/nginx/html; # Document root

# cd /usr/share/nginx/html
# vi

Then save the file

# service nginx restart

Step 17 » Allow port 8080 in the iptables ( Step 4 ) and open your browser

Open your browser and goto http://serverip:8080/info.php ( ) . you could the get PHP info page like below.


Step 17 » Now we can check database connectivity from PHP

Now we can check database connectivity from PHP . create another file dbtest.php in the same location and add the below code to the file and replace your mysql password in the code.

$con = mysql_connect(“localhost”,”root”,”redhat”);
if (!$con)
die(‘Could not connect: ‘ . mysql_error());
echo “Congrats! connection established successfully”;

Step 18» Now access http://serverip:8080/dbtest.php

Now access http://serverip:8080/dbtest.php .if everything is perfect you could get “Congrats!” message as stated in the code.


Default root path is:/use/share/nginx/html

main file and first file is index.html.
You can also put your file for testing and replace any .html with oroginal index.html, also save the another file with same index.html.
You can put with webmin tool, if you are using windows.

Lets have a look .


Now its time to create Self Singned cerficate or make our nginx sever more secure.For your understanding , we will open our website with

How To Create a SSL Certificate on nginx for CentOS 6

A SSL certificate is a way to encrypt a site’s information and create a more secure connection. Additionally, the certificate can show the virtual private server’s identification information to site visitors. Certificate Authorities can issue SSL certificates that verify the server’s details while a self-signed certificate has no 3rd party corroboration.

  you can quickly install it with 2 steps.
Step 1: Install the EPEL repository:
#rpm -Uvh

Install nginx

yum install nginx

Step 2:—Create a Directory for the Certificate

The SSL certificate has 2 parts main parts: the certificate itself and the public key. To make all of the relevant files easy to access, we should create a directory to store them in:

 # mkdir /etc/nginx/ssl
[root@nginxserver html]# cd /etc/nginx/
[root@nginxserver nginx]# ls conf.d         
koi-utf  mime.types  scgi_params   win-utf fastcgi_params koi-win  nginx.conf  uwsgi_params
[root@nginxserver nginx]# mkdir ssl
[root@nginxserver nginx]# ls 
conf.d koi-utf  mime.types  scgi_params  uwsgi_params
fastcgi_params koi-win  nginx.conf  ssl  win-utf
you can see , some directories are already there, and we
have created a directory of ssl , related to our ssl.

Step 3:—Create the Server Key and Certificate Signing Request

Start by creating the private server key. During this process, you will be asked to enter a specific passphrase. Be sure to note this phrase carefully, if you forget it or lose it, you will not be able to access the certificate.

# openssl genrsa -des3 -out server.key 1024
[root@nginxserver ssl]# openssl genrsa -des3 -out server.key 1024
Generating RSA
private key, 1024 bit long modulus
e is 65537
Enter pass phrase
for server.key:
Verifying - Enter
pass phrase for server.key

# openssl genrsa -des3 -out server.key 1024
Have a look at the criteria of generating key.
Genrsra is - practical public-key cryptosystems and is widely 
used for secure data transmission.A file with name server.
key will be created with 1024 bits.

Follow up by creating a certificate signing request:

# openssl req -new -key server.key -out server.csr

This command will prompt terminal to display a lists of fields that need to be filled in.

Here all the fields or csr details will be written to file named server.csr.

When you put this command, it will ask for a key, put thesame paraphase which you had
put in server.key.
[root@nginxserver ssl]# openssl genrsa -des3 -out server.key 1024
Generating RSA
private key, 1024 bit long modulus
e is 65537
Enter pass phrase
for server.key:
Verifying - Enter
pass phrase for server.key:
[root@nginxserver ssl]#  openssl req -new -key server.key -out server.csr
Enter pass phrase
for server.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.What you are about to enter is what 
is called a Distinguished Name or a DN.There are quite a few fields but 
you can leave some blank For some fields there will be a default value,
If you enter '.', the field will be left blank.
Country Name (2letter code) [XX]:IN
State or Province Name (full name) []:New Delhi
Locality Name (eg,city) [Default City]:Mohamadpur
Organization Name (eg, company) [Default Company Ltd]:KVIT
Organizational Unit Name (eg, section) []:KVIT Solutions PVt Ltd.
Common Name (eg,your name or your server's hostname) []:
Email Address []

Please enter the following ‘extra’ attributes to be sent with your certificate request

A challenge password []:redhat
An optional company name []:KVIT

Now our csr has been created.

Step 4:Remove the Passphrase

We are almost finished creating the certificate. However, it would serve us to remove the passphrase. Although having the passphrase in place does provide heightened security, the issue starts when one tries to reload nginx. In the event that nginx crashes or needs to reboot, you will always have to re-enter your passphrase to get your entire web server back online.

Use this command to remove the passphrase:

# cp server.key
# openssl rsa -in -out server.key


Step 5:Sign your SSL Certificate

Your certificate is all but done, and you just have to sign it. Keep in mind that you can specify how long the certificate should remain valid by changing the 365 to the number of days you prefer. As it stands, this certificate will expire after one year.

 # openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

You are now done making your certificate.

[root@nginxserver ssl]# openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Signature ok

subject=/C=IN/ST=New Delhi/L=Mohamadpur/O=KVIT/OU=KVIT Solutions PVt Ltd./CN=

Getting Private key


Step 6: Set Up the Certificate

Open up the SSL config file:

 # vi /etc/nginx/conf.d/ssl.conf

Uncomment within the section under the line HTTPS Server. Match your config to the information below, replacing the in the “server_name” line with your domain name or IP address. If you are just looking to test your certificate, the default root there will work.

[root@nginxserver ~]# vi /etc/nginx/conf.d/ssl.conf

# HTTPS server
server {listen 443;
ssl on;
ssl_certificate /etc/nginx/ssl/server.crt;
ssl_certificate_key /etc/nginx/ssl/server.key;
root /usr/share/nginx/html; # Document root
index index.php index.html index.htm;

To view website with ssl, just open the website with



Click on advanced and then click on proceed to option.

Your website will be open with ssl or https(secured website.)

For any queries, we will be there to help you. And you can mail us at and .For more intresting linux artciles,keep visiting our website and do subscribe to get latest information through mails.

Download PDF


Leave a Reply

Required Captcha *