SlideShare une entreprise Scribd logo
1  sur  57
Télécharger pour lire hors ligne
Nginx:
Accelerate Rails,
HTTP Tricks


Adam Wiggins
Railsconf 2008
Nginx is a webserver
Which means:

Nginx replaces Apache
Nginx replaces Apache
‣Faster
‣Smaller memory footprint
‣More stable under load
‣More secure
But more importantly:
But more importantly:

Nginx is a better fit
for Rails
Apache is the right tool:
‣mod_php
‣owning your own server hardware
Apache is the right tool:
‣mod_php
‣owning your own server hardware


The era now coming to a close.
The era now upon us:

‣Rails
‣cloud computing
The era now upon us:

‣Rails
‣cloud computing

Which both work best with proxying.
Proxying is Nginx’s
primary mechanism for
serving dynamic content
“One thing”
Embrace the constraint
of keeping application
VMs out of the front-end
webserver
Ok cool.
Ok cool.



Wait, there’s something funny
going on here...
Nginx is not a
webserver?
Nginx is an HTTP router
Enough abstraction;
let’s see some code
Proxy balancing example
upstream myapp_mongrels {
   127.0.0.1:3000;
   127.0.0.1:3001;
}

location / {
   proxy_pass http://myapp_mongrels;
}
Memcached in front
location / {
   set $memcached_key $uri;
   memcached_pass 127.0.0.1:11211;
   error_page 404 502 = @myapp;
}

location @myapp {
   internal;
   proxy_pass http://myapp_mongrels;
}
Memcached method filter
location / {
   if ($request_method = GET) {
      set $memcached_key $uri;
      memcached_pass 127.0.0.1:11211;
      error_page 404 502 = @myapp;
      break;
   }

    proxy_pass http://myapp_mongrels;
}
Filtering
Filtering is reaching in
and tinkering with
requests and responses
Separate concerns:
Separate concerns:

‣Filters in your app for
business logic
Separate concerns:

‣Filters in your app for
business logic
‣Filters in your http router
for server infrastructure
Separate concerns:

‣Filters in your app for
business logic
‣Filters in your http router
for server infrastructure
‣Filters in either for
application infrastructure
Separate concerns:

‣Filters in your app for
business logic
‣Filters in your http router
for server infrastructure
‣Filters in either for
application infrastructure
Time to get hardcore:

Custom Nginx modules
http://emiller.info/nginx-modules-guide.html
The problem:

Granular user access
control
The Rails solution:

before_filter
The Rails solution: before_filter
before_filter :authorize

def authorize
  @user = User.find(session[:user_id])
  @resource = request.env['REQUEST_URI']

 redirect_to '/login' unless @user

  redirect_to '/access_denied' unless
              @user.can_access(@resource)
end
Can we do this without
touching the Rails app’s
code?
The Nginx solution:

input filter module
The Nginx solution:

input filter module


ngx_heroku_gate
before_filter :authorize
before_filter :authorize


static ngx_int_t
ngx_heroku_gate_init(ngx_conf_t *cf)
{
  phase =
    cmcf->phases[NGX_HTTP_ACCESS_PHASE];

    h = ngx_array_push(&phase.handlers);
    *h = ngx_heroku_gate_handler;
}
def authorize
  @user = User.find(session[:user_id])
  @resource = request.env['REQUEST_URI']
def authorize
  @user = User.find(session[:user_id])
  @resource = request.env['REQUEST_URI']



static ngx_int_t ngx_heroku_gate_handler
                (ngx_http_request_t *req)
{
  user = get_logged_in_user(
       req->headers_in.cookies);

 app_name = get_app_name(
      req->headers_in.host->value.data);
redirect_to '/login' unless @user
redirect_to '/login' unless @user




if (!user)
{
  redirect_to(req, '/login');
  return NGX_HTTP_MOVED_TEMPORARILY;
}
redirect_to '/access_denied' unless
             @user.can_access(@resource)
redirect_to '/access_denied' unless
             @user.can_access(@resource)


if (!user_can_access(user, app))
{
  redirect_to(req, '/access_denied');
  return NGX_HTTP_MOVED_TEMPORARILY;
}
else
{
  write_heroku_user_header(req, user);
  return NGX_OK;
}
#define X_HEROKU_USER quot;X-Heroku-Userquot;

static void write_heroku_user_header
    (ngx_http_request_t *r, u_char *user)
{
  h = ngx_list_push(
                 &r->headers_in.headers);

    h->hash = 1;
    h->key.len = sizeof(X_HEROKU_USER) - 1;
    h->key.data = (u_char *) X_HEROKU_USER;
    h->value.len = strlen((char *)user);
    h->value.data = user;
}
The Rails solution: before_filter
before_filter :authorize

def authorize
  @user = User.find(session[:user_id])
  @resource = request.env['REQUEST_URI']

 redirect_to '/login' unless @user

  redirect_to '/access_denied' unless
              @user.can_access(@resource)
end
The Nginx solution: input filter
static ngx_int_t
ngx_heroku_gate_handler(ngx_http_request_t *req)
{
  user = get_logged_in_user(req->headers_in.cookies);
  app_name = get_app_name(req->headers_in.host->value.data);

    if (!user) {
      redirect_to(req, '/login');
      return NGX_HTTP_MOVED_TEMPORARILY;
    }

    if (!user_can_access(user, app)) {
      redirect_to(req, '/access_denied');
      return NGX_HTTP_MOVED_TEMPORARILY;
    }
    else {
      write_heroku_user_header(req, user);
      return NGX_OK;
    }
}
A word on performance
Closing thoughts /
the future
HTTP is the enabling
protocol for the era
of cloud computing
http://nginx.ru
http://emiller.info/nginx-modules-guide.html

http://igvita.com/2008/02/11/nginx-and-memcached




Adam Wiggins
http://adam.blog.heroku.com

Contenu connexe

Tendances

ProxySQL Tutorial - PLAM 2016
ProxySQL Tutorial - PLAM 2016ProxySQL Tutorial - PLAM 2016
ProxySQL Tutorial - PLAM 2016
Derek Downey
 
Webinar slides: MySQL & MariaDB load balancing with ProxySQL & ClusterControl...
Webinar slides: MySQL & MariaDB load balancing with ProxySQL & ClusterControl...Webinar slides: MySQL & MariaDB load balancing with ProxySQL & ClusterControl...
Webinar slides: MySQL & MariaDB load balancing with ProxySQL & ClusterControl...
Severalnines
 

Tendances (19)

Clug 2012 March web server optimisation
Clug 2012 March   web server optimisationClug 2012 March   web server optimisation
Clug 2012 March web server optimisation
 
NGINX: The Past, Present and Future of the Modern Web
NGINX: The Past, Present and Future of the Modern WebNGINX: The Past, Present and Future of the Modern Web
NGINX: The Past, Present and Future of the Modern Web
 
Nginx dhruba mandal
Nginx dhruba mandalNginx dhruba mandal
Nginx dhruba mandal
 
cache concepts and varnish-cache
cache concepts and varnish-cachecache concepts and varnish-cache
cache concepts and varnish-cache
 
Happy Browser, Happy User! WordSesh 2019
Happy Browser, Happy User! WordSesh 2019Happy Browser, Happy User! WordSesh 2019
Happy Browser, Happy User! WordSesh 2019
 
High Availability Content Caching with NGINX
High Availability Content Caching with NGINXHigh Availability Content Caching with NGINX
High Availability Content Caching with NGINX
 
PHP conference Berlin 2015: running PHP on Nginx
PHP conference Berlin 2015: running PHP on NginxPHP conference Berlin 2015: running PHP on Nginx
PHP conference Berlin 2015: running PHP on Nginx
 
ProxySQL Tutorial - PLAM 2016
ProxySQL Tutorial - PLAM 2016ProxySQL Tutorial - PLAM 2016
ProxySQL Tutorial - PLAM 2016
 
Running php on nginx
Running php on nginxRunning php on nginx
Running php on nginx
 
Lcu14 Lightning Talk- NGINX
Lcu14 Lightning Talk- NGINXLcu14 Lightning Talk- NGINX
Lcu14 Lightning Talk- NGINX
 
Integrated Cache on Netscaler
Integrated Cache on NetscalerIntegrated Cache on Netscaler
Integrated Cache on Netscaler
 
Massively Scaled High Performance Web Services with PHP
Massively Scaled High Performance Web Services with PHPMassively Scaled High Performance Web Services with PHP
Massively Scaled High Performance Web Services with PHP
 
Where is my cache architectural patterns for caching microservices by example
Where is my cache architectural patterns for caching microservices by exampleWhere is my cache architectural patterns for caching microservices by example
Where is my cache architectural patterns for caching microservices by example
 
Webinar slides: MySQL & MariaDB load balancing with ProxySQL & ClusterControl...
Webinar slides: MySQL & MariaDB load balancing with ProxySQL & ClusterControl...Webinar slides: MySQL & MariaDB load balancing with ProxySQL & ClusterControl...
Webinar slides: MySQL & MariaDB load balancing with ProxySQL & ClusterControl...
 
DockerCon Live 2020 - Securing Your Containerized Application with NGINX
DockerCon Live 2020 - Securing Your Containerized Application with NGINXDockerCon Live 2020 - Securing Your Containerized Application with NGINX
DockerCon Live 2020 - Securing Your Containerized Application with NGINX
 
Unity Makes Strength
Unity Makes StrengthUnity Makes Strength
Unity Makes Strength
 
Supercharging Content Delivery with Varnish
Supercharging Content Delivery with VarnishSupercharging Content Delivery with Varnish
Supercharging Content Delivery with Varnish
 
Postgres connections at scale
Postgres connections at scalePostgres connections at scale
Postgres connections at scale
 
NGINX 101 - now with more Docker
NGINX 101 - now with more DockerNGINX 101 - now with more Docker
NGINX 101 - now with more Docker
 

En vedette

Nginx internals
Nginx internalsNginx internals
Nginx internals
liqiang xu
 
Choosing A Proxy Server - Apachecon 2014
Choosing A Proxy Server - Apachecon 2014Choosing A Proxy Server - Apachecon 2014
Choosing A Proxy Server - Apachecon 2014
bryan_call
 
使用Nginx轻松实现开源负载均衡
使用Nginx轻松实现开源负载均衡使用Nginx轻松实现开源负载均衡
使用Nginx轻松实现开源负载均衡
Cary Yang
 

En vedette (18)

Montreal On Rails 5 : Rails deployment using : Nginx, Mongrel, Mongrel_cluste...
Montreal On Rails 5 : Rails deployment using : Nginx, Mongrel, Mongrel_cluste...Montreal On Rails 5 : Rails deployment using : Nginx, Mongrel, Mongrel_cluste...
Montreal On Rails 5 : Rails deployment using : Nginx, Mongrel, Mongrel_cluste...
 
Nginx internals
Nginx internalsNginx internals
Nginx internals
 
Nginx深度開發與客制化
Nginx深度開發與客制化Nginx深度開發與客制化
Nginx深度開發與客制化
 
Open Source Logging and Monitoring Tools
Open Source Logging and Monitoring ToolsOpen Source Logging and Monitoring Tools
Open Source Logging and Monitoring Tools
 
Choosing A Proxy Server - Apachecon 2014
Choosing A Proxy Server - Apachecon 2014Choosing A Proxy Server - Apachecon 2014
Choosing A Proxy Server - Apachecon 2014
 
高性能Web服务器Nginx及相关新技术的应用实践
高性能Web服务器Nginx及相关新技术的应用实践高性能Web服务器Nginx及相关新技术的应用实践
高性能Web服务器Nginx及相关新技术的应用实践
 
Delivering High-Availability Web Services with NGINX Plus on AWS
Delivering High-Availability Web Services with NGINX Plus on AWSDelivering High-Availability Web Services with NGINX Plus on AWS
Delivering High-Availability Web Services with NGINX Plus on AWS
 
Learn nginx in 90mins
Learn nginx in 90minsLearn nginx in 90mins
Learn nginx in 90mins
 
Application server vs Web Server
Application server vs Web ServerApplication server vs Web Server
Application server vs Web Server
 
Tuning TCP and NGINX on EC2
Tuning TCP and NGINX on EC2Tuning TCP and NGINX on EC2
Tuning TCP and NGINX on EC2
 
NGINX Installation and Tuning
NGINX Installation and TuningNGINX Installation and Tuning
NGINX Installation and Tuning
 
How to secure your web applications with NGINX
How to secure your web applications with NGINXHow to secure your web applications with NGINX
How to secure your web applications with NGINX
 
使用Nginx轻松实现开源负载均衡
使用Nginx轻松实现开源负载均衡使用Nginx轻松实现开源负载均衡
使用Nginx轻松实现开源负载均衡
 
The 3 Models in the NGINX Microservices Reference Architecture
The 3 Models in the NGINX Microservices Reference ArchitectureThe 3 Models in the NGINX Microservices Reference Architecture
The 3 Models in the NGINX Microservices Reference Architecture
 
5 things you didn't know nginx could do
5 things you didn't know nginx could do5 things you didn't know nginx could do
5 things you didn't know nginx could do
 
How To Deploy A Cloud Based Webserver in 5 minutes - LAMP
How To Deploy A Cloud Based Webserver in 5 minutes - LAMPHow To Deploy A Cloud Based Webserver in 5 minutes - LAMP
How To Deploy A Cloud Based Webserver in 5 minutes - LAMP
 
Extending functionality in nginx, with modules!
Extending functionality in nginx, with modules!Extending functionality in nginx, with modules!
Extending functionality in nginx, with modules!
 
Nginx Internals
Nginx InternalsNginx Internals
Nginx Internals
 

Similaire à Nginx: Accelerate Rails, HTTP Tricks

Using Apache as an Application Server
Using Apache as an Application ServerUsing Apache as an Application Server
Using Apache as an Application Server
Phil Windley
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
Ben Lin
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to Tornado
Gavin Roy
 

Similaire à Nginx: Accelerate Rails, HTTP Tricks (20)

Load Balancing Applications with NGINX in a CoreOS Cluster
Load Balancing Applications with NGINX in a CoreOS ClusterLoad Balancing Applications with NGINX in a CoreOS Cluster
Load Balancing Applications with NGINX in a CoreOS Cluster
 
Solving anything in VCL
Solving anything in VCLSolving anything in VCL
Solving anything in VCL
 
NodeJS
NodeJSNodeJS
NodeJS
 
Api Design
Api DesignApi Design
Api Design
 
Hammock, a Good Place to Rest
Hammock, a Good Place to RestHammock, a Good Place to Rest
Hammock, a Good Place to Rest
 
Building and managing applications fast for IBM i
Building and managing applications fast for IBM iBuilding and managing applications fast for IBM i
Building and managing applications fast for IBM i
 
Clojure and the Web
Clojure and the WebClojure and the Web
Clojure and the Web
 
Using Apache as an Application Server
Using Apache as an Application ServerUsing Apache as an Application Server
Using Apache as an Application Server
 
Service Discovery using etcd, Consul and Kubernetes
Service Discovery using etcd, Consul and KubernetesService Discovery using etcd, Consul and Kubernetes
Service Discovery using etcd, Consul and Kubernetes
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development
 
Intro to Rack
Intro to RackIntro to Rack
Intro to Rack
 
Arquitecturas de microservicios - Medianet Software
Arquitecturas de microservicios   -  Medianet SoftwareArquitecturas de microservicios   -  Medianet Software
Arquitecturas de microservicios - Medianet Software
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to Tornado
 
Apache and PHP: Why httpd.conf is your new BFF!
Apache and PHP: Why httpd.conf is your new BFF!Apache and PHP: Why httpd.conf is your new BFF!
Apache and PHP: Why httpd.conf is your new BFF!
 
Using the new WordPress REST API
Using the new WordPress REST APIUsing the new WordPress REST API
Using the new WordPress REST API
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
Switch to Backend 2023
 
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
 
Meetup 2022 - APIs with Quarkus.pdf
Meetup 2022 - APIs with Quarkus.pdfMeetup 2022 - APIs with Quarkus.pdf
Meetup 2022 - APIs with Quarkus.pdf
 

Plus de Adam Wiggins (8)

Waza keynote: Idea to Delivery
Waza keynote: Idea to DeliveryWaza keynote: Idea to Delivery
Waza keynote: Idea to Delivery
 
The Epic Pivot: Heroku's Story
The Epic Pivot: Heroku's StoryThe Epic Pivot: Heroku's Story
The Epic Pivot: Heroku's Story
 
Cloud Services
Cloud ServicesCloud Services
Cloud Services
 
Next-Generation Ruby Deployment with Heroku
Next-Generation Ruby Deployment with HerokuNext-Generation Ruby Deployment with Heroku
Next-Generation Ruby Deployment with Heroku
 
Rails Metal, Rack, and Sinatra
Rails Metal, Rack, and SinatraRails Metal, Rack, and Sinatra
Rails Metal, Rack, and Sinatra
 
Ruby Isn't Just About Rails
Ruby Isn't Just About RailsRuby Isn't Just About Rails
Ruby Isn't Just About Rails
 
Lightweight Webservices with Sinatra and RestClient
Lightweight Webservices with Sinatra and RestClientLightweight Webservices with Sinatra and RestClient
Lightweight Webservices with Sinatra and RestClient
 
rush, the Ruby shell and Unix integration library
rush, the Ruby shell and Unix integration libraryrush, the Ruby shell and Unix integration library
rush, the Ruby shell and Unix integration library
 

Dernier

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
+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@
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Dernier (20)

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
+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...
 
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
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
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
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
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...
 

Nginx: Accelerate Rails, HTTP Tricks