SlideShare a Scribd company logo
1 of 20
Front end servers and
nginx
 What, when and how?
Simple web application

Basic configuration:

•Tomcat, Resin, JBoss, Apache Http + php, ...
•MySQL, PostgreSQL, Oracle, ...


Enough?
What does your server?

General list:

•Process requests to static resource (css, images, etc)
•Process request to dynamic part (servlet).
•Exchange with database.
•Process schedulers, quartz, etc
•Generate reports, calculate statistic...


One day he may say: "enough!". Be ready!
Why sites are dying?

Few problems:

•Weak hardware
•Weak client connection channel
•Lots of requests to static resource (especially images
and video)
•High loads
Front end

Front end is an interface between the user and back
end.

Most popular servers to front end role:
•nginx
•lighthttpd
•apache httpd
•...
Nginx

Popular and productive

Nginx - is a HTTP and reverse proxy server, as well as
mail proxy server, written by Igor Sysoev.
According to Netcraft nginx served or proxied 12.49%
busiest sites in July 2012.
Who are using nginx?

They are:

•Rambler
•Yandex
•Mail.ru
•vk
Features and figures
             •   100 000 connection per server
             •   60 000 requests per second
             •   2.5 Mb per 10 000 keep-alive
                 connections
             •   No threads
Features and figures
What will nginx do?

General function of nginx or
another front end server:

•Static content
•Reserve proxying with caching
•Compression response
•Prepared thumbnails for images
•Uploading, downloading, streaming, ...
Let's start with nginx

Simple configuration

worker_processes 4;

events {
  worker_connections 4096;
}
Virtual hosts
server {
    listen         80 default;
    server_name        www.domain.com;
    root           /home/domain.com


    location / {
        proxy_pass http://localhost:8080;
        proxy_redirect off;
                 proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}
Other virtual hosts

As much as you need:
server {
 listen    80;
 server_name img.domain.com;

    index    index.php;
    root    /home/domain.com/img;
}
Compressing
gzip on;
gzip_min_length 1000;
gzip_proxied   any;
gzip_types     text/plain application/xml text/javascript text/css text/json;
gzip_disable   "msie6";
gzip_comp_level 4;
Thumbnails, proxy to resize
#Image resize location
location ~ ^/preview/(?P<oper>[abc])/(?P<remn>.+) {
           root $path/cache;
           error_page 404 = @fetch;
}

location @fetch {
           root $path/cache;
           proxy_pass http://127.0.0.1:81/$oper/$remn;
           proxy_store on;
}
Thumbnails, resize
location ~ ^/s/(.+) {
     image_filter_buffer 6M;
     alias $path/static/$1;
     try_files "" @404;

     image_filter crop 80 80;
}
location ~ ^/c/[^/]+/(d+|-)x(d+|-)/(.+) {
     set $width $1;
     set $height $2;
     alias $path/static/$3;
     try_files "" @404;
     if ($secure_link = "") { return 404; }
     image_filter crop $width $height;
}
Secured link
location ~ ^/int/(.*)$ {
             alias $path/$1;
             internal;
}

@RequestMapping("/secret/**")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void checkAccess(HttpServletRequest request,
                                               HttpServletResponse response) {
             String img = request.getServletPath();
             String path = "/int/" + img;
             response.setHeader("X-Accel-Redirect", path);
}
Secured link
location ~ ^/int/(.*)$ {
             alias $path/$1;
             internal;
}

@RequestMapping("/secret/**")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void checkAccess(HttpServletRequest request,
                                               HttpServletResponse response) {
             String img = request.getServletPath();
             String path = "/int/" + img;
             response.setHeader("X-Accel-Redirect", path);
}
Uploading
location /upload {
            upload_pass @backend;
            upload_store /location;
            client_max_body_size 15m;
            upload_max_file_size 4m;


            # Set specified fields in request body
            upload_set_form_field $upload_field_name.content_type "$upload_content_type";
            upload_set_form_field $upload_field_name.path "$upload_tmp_path";
            upload_cleanup 400 403 404 405 499 500-505;
}


location @backend {
            proxy_pass http://127.0.0.1:8080;
}
Frontend Servers and NGINX: What, Where and How

More Related Content

What's hot

Getting Started with Couchbase Ruby
Getting Started with Couchbase RubyGetting Started with Couchbase Ruby
Getting Started with Couchbase Ruby
Sergey Avseyev
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统
yiditushe
 

What's hot (20)

Infrastructure as code terraformujeme cloud
Infrastructure as code   terraformujeme cloudInfrastructure as code   terraformujeme cloud
Infrastructure as code terraformujeme cloud
 
MySQL Slow Query log Monitoring using Beats & ELK
MySQL Slow Query log Monitoring using Beats & ELKMySQL Slow Query log Monitoring using Beats & ELK
MySQL Slow Query log Monitoring using Beats & ELK
 
Presto in Treasure Data (presented at db tech showcase Sapporo 2015)
Presto in Treasure Data (presented at db tech showcase Sapporo 2015)Presto in Treasure Data (presented at db tech showcase Sapporo 2015)
Presto in Treasure Data (presented at db tech showcase Sapporo 2015)
 
Getting Started with Couchbase Ruby
Getting Started with Couchbase RubyGetting Started with Couchbase Ruby
Getting Started with Couchbase Ruby
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统
 
Data models in Angular 1 & 2
Data models in Angular 1 & 2Data models in Angular 1 & 2
Data models in Angular 1 & 2
 
GraphQL Los Angeles Meetup Slides
GraphQL Los Angeles Meetup SlidesGraphQL Los Angeles Meetup Slides
GraphQL Los Angeles Meetup Slides
 
How to replace rails asset pipeline with webpack?
How to replace rails asset pipeline with webpack?How to replace rails asset pipeline with webpack?
How to replace rails asset pipeline with webpack?
 
DevOps Fest 2019. Сергей Марченко. Terraform: a novel about modules, provider...
DevOps Fest 2019. Сергей Марченко. Terraform: a novel about modules, provider...DevOps Fest 2019. Сергей Марченко. Terraform: a novel about modules, provider...
DevOps Fest 2019. Сергей Марченко. Terraform: a novel about modules, provider...
 
Spring data iii
Spring data iiiSpring data iii
Spring data iii
 
Drupal 8 Deep Dive: What It Means for Developers Now that REST Is in Core
Drupal 8 Deep Dive: What It Means for Developers Now that REST Is in Core Drupal 8 Deep Dive: What It Means for Developers Now that REST Is in Core
Drupal 8 Deep Dive: What It Means for Developers Now that REST Is in Core
 
Vancouver presentation
Vancouver presentationVancouver presentation
Vancouver presentation
 
Html5 drupal7 with mandakini kumari(1)
Html5 drupal7 with mandakini kumari(1)Html5 drupal7 with mandakini kumari(1)
Html5 drupal7 with mandakini kumari(1)
 
Elk with Openstack
Elk with OpenstackElk with Openstack
Elk with Openstack
 
CouchDB Mobile - From Couch to 5K in 1 Hour
CouchDB Mobile - From Couch to 5K in 1 HourCouchDB Mobile - From Couch to 5K in 1 Hour
CouchDB Mobile - From Couch to 5K in 1 Hour
 
Thijs Feryn - Leverage HTTP to deliver cacheable websites - Codemotion Berlin...
Thijs Feryn - Leverage HTTP to deliver cacheable websites - Codemotion Berlin...Thijs Feryn - Leverage HTTP to deliver cacheable websites - Codemotion Berlin...
Thijs Feryn - Leverage HTTP to deliver cacheable websites - Codemotion Berlin...
 
Influxdb
InfluxdbInfluxdb
Influxdb
 
Big data - Solr Integration
Big data - Solr IntegrationBig data - Solr Integration
Big data - Solr Integration
 
Introducing CouchDB
Introducing CouchDBIntroducing CouchDB
Introducing CouchDB
 
(SDD414) Amazon Redshift Deep Dive and What's Next | AWS re:Invent 2014
(SDD414) Amazon Redshift Deep Dive and What's Next | AWS re:Invent 2014(SDD414) Amazon Redshift Deep Dive and What's Next | AWS re:Invent 2014
(SDD414) Amazon Redshift Deep Dive and What's Next | AWS re:Invent 2014
 

Viewers also liked

Правила хорошего SEO тона в Frontend разработке
Правила хорошего SEO тона в Frontend разработкеПравила хорошего SEO тона в Frontend разработке
Правила хорошего SEO тона в Frontend разработке
Ecommerce Solution Provider SysIQ
 

Viewers also liked (20)

User Behavior: Interacting With Important Website Elements
User Behavior: Interacting With Important Website ElementsUser Behavior: Interacting With Important Website Elements
User Behavior: Interacting With Important Website Elements
 
Эффективный JavaScript - IQLab Frontend Fusion 2012
Эффективный  JavaScript - IQLab Frontend Fusion 2012Эффективный  JavaScript - IQLab Frontend Fusion 2012
Эффективный JavaScript - IQLab Frontend Fusion 2012
 
Databases on Client Side
Databases on Client SideDatabases on Client Side
Databases on Client Side
 
Unexpected achievements 2013
Unexpected achievements 2013Unexpected achievements 2013
Unexpected achievements 2013
 
QA evolution, in pictures
QA evolution, in picturesQA evolution, in pictures
QA evolution, in pictures
 
Testing schools overview
Testing schools overviewTesting schools overview
Testing schools overview
 
Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
 
All things php
All things phpAll things php
All things php
 
Правила хорошего SEO тона в Frontend разработке
Правила хорошего SEO тона в Frontend разработкеПравила хорошего SEO тона в Frontend разработке
Правила хорошего SEO тона в Frontend разработке
 
non-blocking java script
non-blocking java scriptnon-blocking java script
non-blocking java script
 
External Widgets Performance
External Widgets PerformanceExternal Widgets Performance
External Widgets Performance
 
Психология восприятия и UX дизайн
Психология восприятия и UX дизайнПсихология восприятия и UX дизайн
Психология восприятия и UX дизайн
 
Seo and Marketing Requirements in Web Architecture
Seo and Marketing Requirements in Web ArchitectureSeo and Marketing Requirements in Web Architecture
Seo and Marketing Requirements in Web Architecture
 
Going global
Going globalGoing global
Going global
 
Getting to know magento
Getting to know magentoGetting to know magento
Getting to know magento
 
Management and Communications (IPAA)
Management and Communications (IPAA)Management and Communications (IPAA)
Management and Communications (IPAA)
 
Lupan big enterprise ecommerce fusion 2013
Lupan   big enterprise ecommerce fusion 2013Lupan   big enterprise ecommerce fusion 2013
Lupan big enterprise ecommerce fusion 2013
 
Quick Intro to Clean Coding
Quick Intro to Clean CodingQuick Intro to Clean Coding
Quick Intro to Clean Coding
 
Доступность веб-сайтов: WWW для всех?
Доступность веб-сайтов: WWW для всех?Доступность веб-сайтов: WWW для всех?
Доступность веб-сайтов: WWW для всех?
 
Developing for e commerce is important
Developing for e commerce is importantDeveloping for e commerce is important
Developing for e commerce is important
 

Similar to Frontend Servers and NGINX: What, Where and How

Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook
guoqing75
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
WalaSidhom1
 
On secure application of PHP wrappers
On secure application  of PHP wrappersOn secure application  of PHP wrappers
On secure application of PHP wrappers
Positive Hack Days
 
Mobile webapplication development
Mobile webapplication developmentMobile webapplication development
Mobile webapplication development
Ganesh Gembali
 
HTML5: huh, what is it good for?
HTML5: huh, what is it good for?HTML5: huh, what is it good for?
HTML5: huh, what is it good for?
Remy Sharp
 

Similar to Frontend Servers and NGINX: What, Where and How (20)

Express Presentation
Express PresentationExpress Presentation
Express Presentation
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
HTTP Caching and PHP
HTTP Caching and PHPHTTP Caching and PHP
HTTP Caching and PHP
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middleware
 
Thijs Feryn - Leverage HTTP to deliver cacheable websites - Codemotion Berlin...
Thijs Feryn - Leverage HTTP to deliver cacheable websites - Codemotion Berlin...Thijs Feryn - Leverage HTTP to deliver cacheable websites - Codemotion Berlin...
Thijs Feryn - Leverage HTTP to deliver cacheable websites - Codemotion Berlin...
 
Hammock, a Good Place to Rest
Hammock, a Good Place to RestHammock, a Good Place to Rest
Hammock, a Good Place to Rest
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
Boost your website by running PHP on Nginx
Boost your website by running PHP on NginxBoost your website by running PHP on Nginx
Boost your website by running PHP on Nginx
 
How to build a High Performance PSGI/Plack Server
How to build a High Performance PSGI/Plack Server How to build a High Performance PSGI/Plack Server
How to build a High Performance PSGI/Plack Server
 
Bootstrapping multidc observability stack
Bootstrapping multidc observability stackBootstrapping multidc observability stack
Bootstrapping multidc observability stack
 
JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)
JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)
JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)
 
Rack
RackRack
Rack
 
On secure application of PHP wrappers
On secure application  of PHP wrappersOn secure application  of PHP wrappers
On secure application of PHP wrappers
 
Great Developers Steal
Great Developers StealGreat Developers Steal
Great Developers Steal
 
Mobile webapplication development
Mobile webapplication developmentMobile webapplication development
Mobile webapplication development
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
Reverse proxies & Inconsistency
Reverse proxies & InconsistencyReverse proxies & Inconsistency
Reverse proxies & Inconsistency
 
HTML5: huh, what is it good for?
HTML5: huh, what is it good for?HTML5: huh, what is it good for?
HTML5: huh, what is it good for?
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
 

More from Ecommerce Solution Provider SysIQ (13)

Java serialization
Java serializationJava serialization
Java serialization
 
Developing for e commerce is important
Developing for e commerce is importantDeveloping for e commerce is important
Developing for e commerce is important
 
Magento code audit
Magento code auditMagento code audit
Magento code audit
 
User focused design
User focused designUser focused design
User focused design
 
Scalability and performance for e commerce
Scalability and performance for e commerceScalability and performance for e commerce
Scalability and performance for e commerce
 
Going Global
Going GlobalGoing Global
Going Global
 
QA evolution to the present day
QA evolution to the present dayQA evolution to the present day
QA evolution to the present day
 
Manifest of modern engineers
Manifest of modern engineersManifest of modern engineers
Manifest of modern engineers
 
Speed Up Your Website
Speed Up Your WebsiteSpeed Up Your Website
Speed Up Your Website
 
IGears: Template Architecture and Principles
IGears: Template Architecture and PrinciplesIGears: Template Architecture and Principles
IGears: Template Architecture and Principles
 
Interactive web prototyping
Interactive web prototypingInteractive web prototyping
Interactive web prototyping
 
Модульные сетки в реальном мире
Модульные сетки в реальном миреМодульные сетки в реальном мире
Модульные сетки в реальном мире
 
Understanding Annotations in Java
Understanding Annotations in JavaUnderstanding Annotations in Java
Understanding Annotations in Java
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 

Frontend Servers and NGINX: What, Where and How

  • 1. Front end servers and nginx What, when and how?
  • 2. Simple web application Basic configuration: •Tomcat, Resin, JBoss, Apache Http + php, ... •MySQL, PostgreSQL, Oracle, ... Enough?
  • 3. What does your server? General list: •Process requests to static resource (css, images, etc) •Process request to dynamic part (servlet). •Exchange with database. •Process schedulers, quartz, etc •Generate reports, calculate statistic... One day he may say: "enough!". Be ready!
  • 4. Why sites are dying? Few problems: •Weak hardware •Weak client connection channel •Lots of requests to static resource (especially images and video) •High loads
  • 5. Front end Front end is an interface between the user and back end. Most popular servers to front end role: •nginx •lighthttpd •apache httpd •...
  • 6. Nginx Popular and productive Nginx - is a HTTP and reverse proxy server, as well as mail proxy server, written by Igor Sysoev. According to Netcraft nginx served or proxied 12.49% busiest sites in July 2012.
  • 7. Who are using nginx? They are: •Rambler •Yandex •Mail.ru •vk
  • 8. Features and figures • 100 000 connection per server • 60 000 requests per second • 2.5 Mb per 10 000 keep-alive connections • No threads
  • 10. What will nginx do? General function of nginx or another front end server: •Static content •Reserve proxying with caching •Compression response •Prepared thumbnails for images •Uploading, downloading, streaming, ...
  • 11. Let's start with nginx Simple configuration worker_processes 4; events { worker_connections 4096; }
  • 12. Virtual hosts server { listen 80 default; server_name www.domain.com; root /home/domain.com location / { proxy_pass http://localhost:8080; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }
  • 13. Other virtual hosts As much as you need: server { listen 80; server_name img.domain.com; index index.php; root /home/domain.com/img; }
  • 14. Compressing gzip on; gzip_min_length 1000; gzip_proxied any; gzip_types text/plain application/xml text/javascript text/css text/json; gzip_disable "msie6"; gzip_comp_level 4;
  • 15. Thumbnails, proxy to resize #Image resize location location ~ ^/preview/(?P<oper>[abc])/(?P<remn>.+) { root $path/cache; error_page 404 = @fetch; } location @fetch { root $path/cache; proxy_pass http://127.0.0.1:81/$oper/$remn; proxy_store on; }
  • 16. Thumbnails, resize location ~ ^/s/(.+) { image_filter_buffer 6M; alias $path/static/$1; try_files "" @404; image_filter crop 80 80; } location ~ ^/c/[^/]+/(d+|-)x(d+|-)/(.+) { set $width $1; set $height $2; alias $path/static/$3; try_files "" @404; if ($secure_link = "") { return 404; } image_filter crop $width $height; }
  • 17. Secured link location ~ ^/int/(.*)$ { alias $path/$1; internal; } @RequestMapping("/secret/**") @PreAuthorize("hasRole('ROLE_ADMIN')") public void checkAccess(HttpServletRequest request, HttpServletResponse response) { String img = request.getServletPath(); String path = "/int/" + img; response.setHeader("X-Accel-Redirect", path); }
  • 18. Secured link location ~ ^/int/(.*)$ { alias $path/$1; internal; } @RequestMapping("/secret/**") @PreAuthorize("hasRole('ROLE_ADMIN')") public void checkAccess(HttpServletRequest request, HttpServletResponse response) { String img = request.getServletPath(); String path = "/int/" + img; response.setHeader("X-Accel-Redirect", path); }
  • 19. Uploading location /upload { upload_pass @backend; upload_store /location; client_max_body_size 15m; upload_max_file_size 4m; # Set specified fields in request body upload_set_form_field $upload_field_name.content_type "$upload_content_type"; upload_set_form_field $upload_field_name.path "$upload_tmp_path"; upload_cleanup 400 403 404 405 499 500-505; } location @backend { proxy_pass http://127.0.0.1:8080; }