You are on page 1of 17

Ngnix The Basics

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?


 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
 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 HTTPis considered the most important.

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 Nginxgrabbed the stage.
What is C10K Problem?
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.

Quick Fact
We are not far away from the C10M problem!

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:

o FastCGI

o uwsgi

o 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:

o Round Robin
o Least Connected

o IP hash

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.

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.

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

o 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:


o /data/www: place a file named index.html inside it.
o /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!

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

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.
Nginx Course summary
Congratulations! You have successfully completed the course on Nginx.

You are now ready to start hosting a web application from your local machine, convert Nginx
as a reverse proxy for other web servers and more.

QUIZ:

1. ___________ webserver was introduced primarily to support Java servlets. APACHIE TOMCAT


2. IBM Websphere was introduced in the year __________. 1998
3. Nginx supports __________ through round robin algorithm. LOAD BALANCING
4. ___________ was introduced in the year 1995. APACHE HTTP
5. Choose the best option. Nginx is a ___________. A) Webserver B) Reverse proxy C) Loadbalancer D)
Hub A,B,C
6. Nginx has become popular as it resolves __________. C10K
7. Apache cannot handle 10K connections because it is a _____________ webserver. THREAD
BASED
8. Nginx was introduced in the year _________. 1999
9. World's first web server was developed in_____________. 1990'S
10. Nginx supports __________ through SCGI protocol. REVERSE PROXY
11. Which of the following line can be used to install Nginx? APT GET INSTALL NGINX
12. You can ask Nginx to refresh its configuration file using _____________. RELOAD
13. It is always recommended to install ___________ version of Nginx. DEVELOPMENT
14. For smooth shutdown of Nginx, you must use _____________. QUIT
15. Nginx can be started using _____________. SERVICE NGINX START
16. Each resource has its own _____________. URI
17. The event-polling nature of Nginx can be dealt with using _____________. EVENTS
18. worker_connections is a directive contained within ___________. EVENTS
19. In nginx.conf, a block of lines defined within a pair of curly braces is called _____________.
CONTEXT
20. 127.0.0.1 is an IP address of _____________. All web servers
21. When you configure Nginx as a reverse proxy for Apache, both may listen to a same port. F
22. A server block may contain _________ location block Any
23. If you define more than one default server, Nginx will work as multiple domain server
24. A server block may contain another server block F

You might also like