Nginx

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 13

How many times have you visited http://www.google.com?

The moment you press enter, your browser displays the home page of Google.

Do you know the process behind it?

What Happens Then?


Loading image..
You enter the URL in your browser.

The browser sends an HTTP request to the web server.

The web server detects the corresponding web resource.

The web server sends back the HTTP response to the browser.

The browser displays the page for you.

Know the Terms

Web client/UserAgent: May be a browser/CURL/Telnet.

Web application: Any application hosted through the web. Ex: Website

Web Server: A system that hosts one or more web application(s).

Web Resource: Any static or dynamic file (HTML/JSON/PDF/..), served by a web


application. Each resource has its unique URL.

Protocol: A set of rules agreed by both the parties for standardizing the
communication.

What is a Web Server?

A web server is a computer that processes the Hyper Text Transfer Protocol (HTTP)
requests and sends back the HTTP response to clients.

Apache, IIS and Nginx are the most popular web servers.

Need of a Protocol
Loading image..
When two individuals communicate with each other, they should know a common
language to convey their thoughts.
The same way when two systems need to communicate, they should follow a common mode
of communication; hence they agree upon a common set of rules called a Protocol
that governs the communication.
TCP, UDP, FTP and HTTP are some of the communication protocols out of which HTTP is
considered the most important.
5 of 13
HTTP - The Hero

Wikipedia defines HTTP as the foundation of the data communication for WWW.

It is a client-server protocol based on request-response model.

HTTP Request: Client sends a request with the URL of an HTML page.

HTTP Response: The web server transmits back the requested HTML page via an HTTP
response.

The First Web Server

W3C httpd or CERN httpd is the world's first web server developed in 1990's by Tim
Berners-Lee and his team at CERN (European Organization for Nuclear Research).

Adept Web Servers

Both Apache HTTP server and IIS were introduced in the year 1995, and even now they
are reigning as two giants in the world of web technology.

IBM Websphere was introduced in the year 1998.

In 1999, Apache released its TOMCAT server to support Java servlets and JSPs.

The Entry of Nginx

One fine morning in 1999, Dan Kegal came up with an issue that all the traditional
web servers are incapable of handling 10K concurrent clients/connections and named
it C10K problem.

The C10K problem is the main reason why the next giant of the field called Nginx
grabbed the stage.

What is C10K Problem?


Loading image..
Threaded servers like Apache cannot handle 10K connections because,

Each connection creates a new thread.

The kernel uses O(n^2)* algorithm, so 10K threads are not possible.

So, the engineers started moving away from threaded servers to event-driven servers
like Nginx

*: The Big O notation used for calculating time/space complexity of algorithms.

What is Nginx?

Pronounced as EngineX.

Open source web server or reverse proxy server.


Can also be utilized for server load balancing and HTTP cache.

Nginx as a Web Server

The Nginx server processes the HTTP requests and sends back the HTTP response to
the client.

Nginx handles HTTP requests by asynchronous, event-driven method.

Nginx as a Reverse Proxy

A reverse proxy is also a proxy server that retrieves data from all the resources
on behalf of its client.

Nginx supports reverse proxying through the following protocols:

FastCGI

uwsgi

SCGI

NginX as a Load Balancer

Nginx acts as an effective load balancer for HTTP by distributing requests across
multiple applications.

It improves the performance, reduces the latency and also maximizes the throughput.

Nginx supports the following algorithms for load balancing:

Round Robin

Least Connected

IP hash

4 of 5

Nginx Versions

Nginx has three versions:

Development: Highly recommended as it includes fixes for bugs in the stable


version.

Stable: Tested and accepted by a community of users and testers.

Legacy: Not recommended as it is an outdated one.

Two Modes of Installation


You can furnish your Nginx server by,

Building it from source

Installing it from binary packages

Installation through binary package needs a package manager such as yum.

Nginx with Windows

The easiest way to install Nginx is with Windows.

Go to the official Nginx installation page for Windows

Download the latest/required Windows release.

Extract it anywhere.

That is it; you are ready to go!

Hold On!
Nginx is easy to install with windows, but what about the performance?

A Worker (Nginx instance) cannot handle more than 1024 connections concurrently.

Only one worker can be used at a time.

Windows Vista or later versions do not support cache module.

So, Nginx with windows is no longer effective as Nginx with Linux!

Installation via Source?

Opportunities:

Easy to use third party modules.

The latest version can be used immediately.

Obstacles:

Complicated installation procedure.

You should always keep yourself updated.

7 of 13

Installing from Source


Run the following command to install the Nginx dependencies automatically.
From apt:

sudo apt-get build-dep Nginx

From yum:
sudo yum install pcre-devel zlib-devel openssl-devel

Now you are ready to compile Nginx.

Ensure that you are in the directory where you wish to install NginX.

Run the following command

wget http://www.nginx.org/download/nginx-1.3.15.tar.gz

tar zxf nginx-1.3.15.tar.gz

cd nginx-1.3.15

./configure --help

If you have decided the modules to be included, run the command below.

./configure �with-foo

To know about each modules, visit the official link.

Run these commands to compile

make

make install

Installation via Binary Package?


Benefits

Easy installation procedure.

No need to follow the updates.

Obstacles

Limited support of third party modules.

Picking the best version is challenging.

Sometimes your version may be an outdated one.

Installing from Binary Package


Using native packages, we can quickly install Nginx by running the following
command

yum install nginx

or
apt-get install nginx

If the native package is old, it is good to install from binary packages provided
by Nginx

In yum, create a file /etc/yum.repos.d/nginx.repo and add these lines

[nginx]

name=nginx repo

baseurl=http://nginx.org/packages/OS/OSRELEASE/$basearch/

gpgcheck=0

enabled=1

Here, if OS in CentOS then OS should be given centos, and OSRELEASE is the version
number.

In apt for Debian OS, add the following to /etc/apt/sources.list

deb http://nginx.org/packages/debian/ squeezenginx

deb-src http://nginx.org/packages/debian/ squeezenginx

In apt for Ubuntu OS, add the following

deb http://nginx.org/packages/ubuntu/ codenamenginx

deb-src http://nginx.org/packages/ubuntu/ codenamenginx

Here, the codename can be substituted with lucid, quantal , oneiric or precise
accordingly.
Then run the following commands

apt-get update

apt-get install nginx

Starting Nginx
Using a script is the best way of starting Nginx.

If you have installed Nginx through binary files, you can directly run the command
below:

service nginx start

If you have installed by other means, you need to install the script on your own.

To get help on quick setup, visit the Nginx community page for InitScripts

Download the platform specific init script, save it to /etc/rc.d/init.d/nginx


Edit the path as per your system in the file and run the following command:

chmod +x /etc/rc.d/init.d/nNginx

Then run the foresaid command for starting Nginx.

Controlling Nginx
We have already started Nginx successfully. Let us see how to control it:

Nginx quick shut down

nginx -s stop

Nginx smooth shutdown:

nginx -s quit

Reload nginx.conf

nginx -s reload

Reopen the log files:

ngix -s reopen

Locate Your Configuration File

nginx.conf is the configuration file and its location depends on how you have
installed Nginx.

Via binary package: /etc/nginx/nginx.conf

Via source: if you have chosen the default path, then search for the subfolder
/conf inside /usr/local/nginx

Understand nginx.conf
Take a look at the file; you will find its layered structure.

Each block defined within a pair of curly braces {} is a context.

Directive and Contexts are the two important terms to understand the configuration
file of Nginx.

Swipe further to know the configuration file better.

Directives and Contexts


Directives:

A directive is an identifier used to distinguish various configuration options


available in Nginx.
Contexts:
The diverse sections of the configuration file are termed as Contexts.

main context
main is the first context that refers to the nginx.conf file itself.

worker_processes and user are the two essential directives contained within main
context.

The main context may have various sub contexts out of which events and http are
considered the two crucial sub contexts.

Two Essential Directives


worker_processes: How many workers should Nginx allow to run concurrently.

user: The user or group under which Nginx should run those configurations.

Two Crucial subcontexts - events


It handles directives that deal with the event-polling nature of Nginx.

Nginx gives the optimal configuration automatically. Hence we can ignore this.

worker_connections is an important directive in events that refers to the number of


connections a worker can handle.

Two Crucial subcontexts - http


It deals with everything associated with HTTP and the one you will be working with
most of the time in main.

The server is an important subcontext of http and is equivalent to a virtual host.

server and location


server handles the configuration directives based on the host under which your
sites are located.

location is a subcontext of server context. It is used to match Uniform Resource


Identifier (URI).

Define Your Static Server First!


The main task of a web server is to serve files (web resources) on request (Http
requests). Let's see how to setup a server:

First, create the following two directories:

/data/www: place a file named index.html inside it.

/data/images: place some images inside it.

Modify your configuration file.

Reload the configuration file.

nginx -s reload
Modifying nginx.conf
Open the configuration file.

Find the http block.

Add a server block to it.

Add two location blocks to it to serve html files and images.

Finally, your server block should look like this:

server {

location / {

root /data/www;

location /images/ {

root /data;

Move forward to understand how it works!

2 of 12

More on Location block


The format of defining a location block is:

location modifier match {

. . .

modifier is optional.

match defines what should be checked against the URI requested by the client.

Modifiers
No modifier: considered the prefix modifier. Ex: location / will match any URI
beginning with /.
= modifier: matches the exact URI. Ex: location /foo will match only

/foo URI.

~ modifier: case sensitive regular expression. Ex: location ~.(png | jpg | jpeg)$
will match any URI ending with .png or .jpg or .jpeg.

~* modifier: case insensitive regular expression. Ex: location ~.(png | jpg)$* will
match any URI ending with .png or .jpg or .PNG or .JPG.

^~ modifier: will match the prefix value. Ex: location ^~ /play/ will match any URI
beginning with /play/.

Ready for Your Own Proxy?


Create a folder data/play and add an index.html and modify the server block:

server {

location / {

proxy_pass http://localhost:8080/;

location ~ \.(gif|jpg|png)$ {

root /data/images;

Ready for Your Own Proxy?...


Add one more server block to nginx.conf

server {

listen 8080;

root /data/play;

location / {

Apache with Nginx


Loading image..
Let us see how to use Nginx as a reverse proxy for Apache.

Install Apache2.

Configure the ports using ports.config file.


Listen 8000

Open the file /etc/apache2/sites-available/000-default.conf and change the virtual


host parameters.

<VirtualHost 127.0.0.1:8000>

Restart Apache using the following command

service apache2 restart

Install Nginx and configure it to pass the requests to Apache using the following
configuration.

server {

listen 80 default_server;

listen [::]:80 default_server;

root /var/www/html;

index index.html index.htm index.nginx-debian.html;

server_name _;

location / {

proxy_pass http://localhost:8000;

include /etc/nginx/proxy_params;

Reload Nginx and ping localhost from your browser.

What is CORS?
Cross-Origin Resource Sharing (CORS) is a way of accessing the restricted resources
of one domain from another domain.

Traditionally CORS was restricted by web browsers for security reasons.

Modern web browsers support client side elements for CORS.

The server must be capable of handling new request types with added headers for
CORS

CORS sample code


Here is a sample code, which enables www.play.com to access resources from
www.talk.com

set $cors '';


if ($http_origin ~ '^https?://(www.play.com|www.talk.com)') {

set $cors 'true';

if ($cors = 'true') {

add_header 'Access-Control-Allow-Origin' $http_origin always;

add_header 'Access-Control-Allow-Credentials' 'true' always;

add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;

add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-


Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-
Requested-With' always;

# required to be able to read Authorization header in frontend

#add_header 'Access-Control-Expose-Headers' 'Authorization' always;

if ($request_method = 'OPTIONS') {

# Tell client that this pre-flight info is valid for 20 days

add_header 'Access-Control-Max-Age' 1728000;

add_header 'Content-Type' 'text/plain charset=UTF-8';

add_header 'Content-Length' 0;

return 204;

Gzipping
1
Nginx offers Gzipping of JS, HTML and CSS files as a core feature which improves
your load time.

Pre-Gzipping
2
Instead of compressing files on each request, the site assets will be pre-
compressed and stored.

Full-page Micro Cache


3
Any page without user-specific data can be stored in Nginx to avoid disturbing the
backend application.
GeoIP Lookups
4
By utilizing the MaxMind GeoIP database (Paid/free version), you can do GeoIP
lookups with Nginx.

Video Streaming
5
FLV and MP4 modules can be used to stream videos with Nginx.

You might also like