SlideShare a Scribd company logo
NGINX SCRIPTING
EXTENDING NGINX FUNCTIONALITIES WITH LUA
          Tony Fabeen / @tonyfabeen / SlimStacks
WHO AM I
NGINX ("ENGINE-X")
High performance HTTP, POP/IMAP and reverse proxy server.
Started in 2002 by Igor Sysoev, public in 2004.
Entirely written in C.
Hosts nearly 12.18% of active sites across all domains.
Nginx.com in 2011.
MASTER WORKER MODEL
$p ax|ge nix
        s u rp gn

ro 339..nix mse poes/p/gn/bnnix
 ot 12 . gn: atr rcs otnixsi/gn

ww 330..nix wre poes
 w 13 . gn: okr rcs
Nginx Scripting - Extending Nginx Functionalities with Lua
MASTER PROCESS
reading and validating configuration
creating, binding and closing sockets
starting, terminating and maintaining the configured number of w r e
                                                                okr
processes
re-opening log files
compiling embedded Perl scripts
WORKER PROCESS
Do all important stuff
Handle connection from clients
Reverse Proxy and Filtering functionalities
REQUEST PROCESSING
Nginx Scripting - Extending Nginx Functionalities with Lua
REQUEST PHASES
SERVER REWRITE PHASE
request URI transformation on virtual server level
FIND CONFIG PHASE
configuration location lookup
REWRITE PHASE
request URI transformation on location level
ACCESS PHASE
access restrictions check phase
TRY FILES PHASE
try_files directive processing phase
CONTENT PHASE
content generation phase
LOG PHASE
 logging phase
MODULARITY
Core Module
Functional Modules
CORE MODULE
Event Loop
Module execution control
FUNCTIONAL MODULES
Read from / Write to Network and Storage
Transform Content
Outbound Filtering
Server Side Includes
Upstream Server communication
...etc
LUA ON THE STAGE
A BIT OF LUA
 Created in Brazil
 Portable
 Simple
 Small
 Easy to embed
 Fast
OSS USING LUA
LUA NGINX MODULE
           https://github.com/chaoslawful/lua-nginx-module/
Created by TaoBao.com Engineers
High concurrent and non-blocking request processing
Programs can be written in the plain-old sequential way
Nginx takes care of I/O operations and Lua Nginx Module restore the
context and resume the program logic
LUA NGINX MODULE
         https://github.com/chaoslawful/lua-nginx-module
Introduces directives for running Lua inside Nginx
Exposes the Nginx environment to Lua via an Api
It's fast
Is even faster when compiled with LUA JIT(Just in Time Compiler)
NGINX LUA API
DIRECTIVES
Configuration directives serve as gateways to the Lua API within the
                           nginx.conf file.

     cnetb_u LASRP_TIG
     otn_yla U_CITSRN
     rwieb_u LASRP_TIG
     ert_yla U_CITSRN
     acs_ylaLASRP_TIG
     cesb_u U_CITSRN
     cnetb_u_iePT_OLASRP_IE
     otn_ylafl AHT_U_CITFL
     rwieb_u_iePT_OLASRP_IE
     ert_ylafl AHT_U_CITFL
     acs_ylafl PT_OLASRP_IE
     cesb_u_ie AHT_U_CITFL
      Unless you set l a c d _ a h to o f modules will be loaded once on the first request.
                      u_oecce f ,
NGX PACKAGE
Nginx Environment is exposed via n x
                                  g package
     nxagulag
      g.r.r_r
     nxvrVRAL_AE
      g.a.AIBENM
     nxhae.EDRATIUE
      g.edrHAE_TRBT
     nxcx
      g.t
HELLO WORLD !
  lcto /el-srb-u {
   oain hloue-yla
    dfuttp "etpan;
     eal_ye tx/li"
    cnetb_u '
     otn_yla
      nxsy"el," nxvragnm,""
       g.a(Hlo , g.a.r_ae !)
    ';
  }

  lcto /el-srb-gn {
   oain hloue-ynix
    eh "el,$r_ae!;
     co Hlo agnm "
  }

$cr ht:/oahs/el-srb-u?aeDvnap
  ul tp/lclothloue-ylanm=eISma
 Hlo Dvnap !
  el, eISma
$cr ht:/oahs/el-srb-gn?aeDvnap
  ul tp/lclothloue-ynixnm=eISma
 Hlo Dvnap !
  el, eISma
NGINX VARS
    lcto /csignixag {
     oain aesn-gn-rs
      st$is 3;
      e frt 5
      st$eod6;
      e scn 5

        stb_u $u '
         e_yla sm
          rtr nxvrfrt+nxvrscn
           eun g.a.is  g.a.eod
        ';

        eh "h smi $u"
        co Te u s sm;
    }

$cr ht:/oahs/csignixag
  ul tp/lclotaesn-gn-rs
 Tesmi 9
  h u s 9
NGINX SUBREQUESTS
lcto /u-urqet {
oain lasbeuss
 cnetb_u '
  otn_yla
  lclrsos =nxlcto.atr(/el-srb-gn?ae
   oa epne   g.oaincpue"hloue-ynixnm=
Dvnap"
eISma)
  i rsos.tts> 50te
   f epnesau = 0 hn
     nxei(epnesau)
     g.xtrsos.tts
  ed
   n

      nxsau =rsos.tts
       g.tts  epnesau
      nxsyrsos.oy
       g.a(epnebd)
    ';
}

$cr ht:/oahs/u-urqet
  ul tp/lclotlasbeuss
 Hlo Dvnap !
  el, eISma
NON BLOCKING I/O SUBREQUESTS
lcto /nltc-nrmn {
 oain aayisiceet
     cnetb_u '
      otn_yla
      lclrsos =nxlcto.atr(/ei"
       oa epne  g.oaincpue"rds,
          {rs={m ="nr,ky=nxvragln})
           ag  cd  ic" e  g.a.r_ik}
      nxsy"nrmne t :,nxvragln)
       g.a(Iceetd o " g.a.r_ik
     ';

}
lcto /ei {
 oain rds

    itra;
     nenl

    stuecp_r $e $r_e;
     e_nsaeui ky agky
    stuecp_r $m $r_m;
     e_nsaeui cd agcd

    rds_ur $m $e;
     ei2qey cd ky
    rds_as1700167;
     ei2ps 2...:39

}


$cr ht:/oahs/nltc-nrmn?ikht:/w.eismacmb
  ul tp/lclotaayisiceetln=tp/wwdvnap.o.r

    Iceetdt :tp/wwdvnap.o.r
     nrmne o ht:/w.eismacmb
FILTERS
HEADER FILTERS
lcto /{
 oain
  poyps ht:/oahs:00
   rx_as tp/lclot88;
  hae_itrb_u 'g.edrSre ="yLtl Sre";
   edrfle_yla nxhae.evr  M ite evr'
}

$cr - - HA ht:/oahs/edrfle
  ul i X ED tp/lclothae-itr
 HT/. 20O
  TP11 0 K
 Dt:Sn 0 Sp21 2:81 GT
  ae u, 9 e 02 11:1 M
 Sre:M Ltl Sre
  evr y ite evr
 CnetTp:tx/tlcastuf8
  otn-ye ethm;hre=t-
 CnetLnt:49
  otn-egh 4
 Cneto:ke-lv
  oncin epaie
 Sau:20O
  tts 0 K
 XFaeOtos smoii
  -rm-pin: aergn
 XXSPoeto:1 md=lc
  -S-rtcin ; oebok
 XCsae ps
  -acd: as
 XRc-ah:ms
  -akCce is
BODY FILTERS
lcto /oyfle {
oain bd-itr
 eh "ycnet;
  co M otn"

    bd_itrb_u '
     oyfle_yla
      nxag1 =srn.sbnxag1,"y,"or)
       g.r[]  tiggu(g.r[] M" Yu"
      nxag2 =tu -stefo ls canbfe
       g.r[]  re -e o r at hi ufr
    ';
}

$cr ht:/oahs/oyfle
  ul tp/lclotbd-itr
 Yu cnet
  or otn
COSOCKETS
Non Blocking, of course
Communicate via TCP or Unix domain sockets
Keepalive mechanism avoid connect/close for each request
COSOCKETS
lcto /ecce-rmla{
oain mmahdfo-u
 cnetb_u '
  otn_yla
  lclsc =nxsce.onc(17001,121
   oa ok  g.oktcnet"2..." 11)
  lclbts er=sc:ed"e fobrrn)
   oa ye, r  oksn(st o a"

     i ntbtste
      f o ye hn
       nxsy"aldt sn. " er
        g.a(fie o ed. n, r)
       rtr
        eun
     ed
      n

     lcldt =sc:eev(
      oa aa   okrcie)
     i ntdt te
      f o aa hn
       nxsy"aldt rciedt."
        g.a(Fie o eev aa.n)
     ed
      n

      nxsy"eut:" dt)
       g.a(Rsl  , aa
    ';

}
SOME LIBRARIES USING PURE COSOCKETS
    https://github.com/agentzh/lua-resty-memcached
    https://github.com/agentzh/lua-resty-redis
    https://github.com/agentzh/lua-resty-mysql
SUMMARY
The Nginx architecture is excellent for highly scalable applications.
Nginx can do a variety of things thanks to module extensions, and one can
resuse those extensions by issuing sub-requests in Lua.
lua-nginx-module makes use of the evented architecture in Nginx,
providing a powerful and performant programming environment.
It's possible to do 100% non-blocking I/O with readable code.
REFERENCES
http://www.aosabook.org/en/nginx.html
http://openresty.org
http://www.evanmiller.org/nginx-modules-guide.html
http://wiki.nginx.org/HttpLuaModule
BOOKS
QUESTIONS

   ?
THANKS
http://www.twitter.com/tonyfabeen

http://www.linkedin.com/in/tonyfabeen

https://github.com/tonyfabeen
Nginx Scripting - Extending Nginx Functionalities with Lua

More Related Content

PDF
Using ngx_lua in UPYUN
PDF
Roll Your Own API Management Platform with nginx and Lua
PDF
Lua tech talk
PDF
PDF
RestMQ - HTTP/Redis based Message Queue
PDF
Redis & ZeroMQ: How to scale your application
PDF
Redis as a message queue
ODP
nginx: writing your first module
Using ngx_lua in UPYUN
Roll Your Own API Management Platform with nginx and Lua
Lua tech talk
RestMQ - HTTP/Redis based Message Queue
Redis & ZeroMQ: How to scale your application
Redis as a message queue
nginx: writing your first module

What's hot (20)

PDF
Using ngx_lua in UPYUN 2
PDF
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
PDF
Node.js streaming csv downloads proxy
PDF
Application Logging in the 21st century - 2014.key
KEY
Streams are Awesome - (Node.js) TimesOpen Sep 2012
PDF
OWASP Proxy
PDF
Perl Memory Use 201209
PDF
Relayd: a load balancer for OpenBSD
PDF
Using ngx_lua in upyun 2
PDF
tdc2012
PDF
Bootstrapping multidc observability stack
PPT
On UnQLite
PDF
Nodejs - A quick tour (v6)
PDF
Pf: the OpenBSD packet filter
PDF
Новый InterSystems: open-source, митапы, хакатоны
PDF
Tuning Solr for Logs
PDF
Node.js in production
PDF
PL/Perl - New Features in PostgreSQL 9.0 201012
PDF
Top Node.js Metrics to Watch
ODP
Integrating icinga2 and the HashiCorp suite
Using ngx_lua in UPYUN 2
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Node.js streaming csv downloads proxy
Application Logging in the 21st century - 2014.key
Streams are Awesome - (Node.js) TimesOpen Sep 2012
OWASP Proxy
Perl Memory Use 201209
Relayd: a load balancer for OpenBSD
Using ngx_lua in upyun 2
tdc2012
Bootstrapping multidc observability stack
On UnQLite
Nodejs - A quick tour (v6)
Pf: the OpenBSD packet filter
Новый InterSystems: open-source, митапы, хакатоны
Tuning Solr for Logs
Node.js in production
PL/Perl - New Features in PostgreSQL 9.0 201012
Top Node.js Metrics to Watch
Integrating icinga2 and the HashiCorp suite
Ad

Viewers also liked (20)

PDF
OAuth and OpenID Connect for Microservices
PDF
Stateless authentication for microservices
PDF
Nginx Internals
PDF
Hacking Nginx at Taobao
PDF
Nginx+lua在阿里巴巴的使用
PPTX
Accelerating Nginx Web Server Performance
PDF
Running PHP on Nginx / PHP wgtn
PPTX
Webpage Caches - the big picture (WordPress too)
PPTX
5 critical-optimizations.v2
PPTX
Web Performance, Scalability, and Testing Techniques - Boston PHP Meetup
ODP
Caching and tuning fun for high scalability @ FOSDEM 2012
PDF
基于OpenResty的百万级长连接推送
PDF
High Performance Php My Sql Scaling Techniques
PDF
PPTX
Maximizing PHP Performance with NGINX
PDF
Practical ngx_mruby
PDF
Nginx pres
PDF
Как и зачем создавать NginX-модуль - теория, практика, профит / Василий Сошни...
PDF
Using ngx_lua / lua-nginx-module in pixiv
PDF
Devinsampa nginx-scripting
OAuth and OpenID Connect for Microservices
Stateless authentication for microservices
Nginx Internals
Hacking Nginx at Taobao
Nginx+lua在阿里巴巴的使用
Accelerating Nginx Web Server Performance
Running PHP on Nginx / PHP wgtn
Webpage Caches - the big picture (WordPress too)
5 critical-optimizations.v2
Web Performance, Scalability, and Testing Techniques - Boston PHP Meetup
Caching and tuning fun for high scalability @ FOSDEM 2012
基于OpenResty的百万级长连接推送
High Performance Php My Sql Scaling Techniques
Maximizing PHP Performance with NGINX
Practical ngx_mruby
Nginx pres
Как и зачем создавать NginX-модуль - теория, практика, профит / Василий Сошни...
Using ngx_lua / lua-nginx-module in pixiv
Devinsampa nginx-scripting
Ad

Similar to Nginx Scripting - Extending Nginx Functionalities with Lua (20)

PDF
Noah Zoschke at Waza 2013: Heroku Secrets
PDF
Beginner workshop to angularjs presentation at Google
PDF
Tips on how to improve the performance of your custom modules for high volume...
PDF
Refactoring to symfony components
PDF
Marko Gargenta_Remixing android
PDF
linux-namespaces.pdf
ODP
PostgreSQL Administration for System Administrators
ODP
Perl - laziness, impatience, hubris, and one liners
PDF
Null Bachaav - May 07 Attack Monitoring workshop.
PDF
Keep it simple web development stack
PDF
Introduction to Ansible
PDF
An Introduction to CSS Preprocessors
PDF
php[world] 2016 - You Don’t Need Node.js - Async Programming in PHP
PDF
Zend con 2016 - Asynchronous Prorgamming in PHP
PDF
Javascript fundamentals for php developers
PDF
Awesome Traefik - Ingress Controller for Kubernetes - Swapnasagar Pradhan
PPTX
Attack monitoring using ElasticSearch Logstash and Kibana
PDF
CoreOS: Control Your Fleet
PDF
JavaFX, because you're worth it
PDF
Debugging: Rules And Tools - PHPTek 11 Version
Noah Zoschke at Waza 2013: Heroku Secrets
Beginner workshop to angularjs presentation at Google
Tips on how to improve the performance of your custom modules for high volume...
Refactoring to symfony components
Marko Gargenta_Remixing android
linux-namespaces.pdf
PostgreSQL Administration for System Administrators
Perl - laziness, impatience, hubris, and one liners
Null Bachaav - May 07 Attack Monitoring workshop.
Keep it simple web development stack
Introduction to Ansible
An Introduction to CSS Preprocessors
php[world] 2016 - You Don’t Need Node.js - Async Programming in PHP
Zend con 2016 - Asynchronous Prorgamming in PHP
Javascript fundamentals for php developers
Awesome Traefik - Ingress Controller for Kubernetes - Swapnasagar Pradhan
Attack monitoring using ElasticSearch Logstash and Kibana
CoreOS: Control Your Fleet
JavaFX, because you're worth it
Debugging: Rules And Tools - PHPTek 11 Version

Recently uploaded (20)

PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
sap open course for s4hana steps from ECC to s4
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Approach and Philosophy of On baking technology
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Big Data Technologies - Introduction.pptx
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
KodekX | Application Modernization Development
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Encapsulation theory and applications.pdf
PPTX
Spectroscopy.pptx food analysis technology
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
MYSQL Presentation for SQL database connectivity
Understanding_Digital_Forensics_Presentation.pptx
sap open course for s4hana steps from ECC to s4
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Programs and apps: productivity, graphics, security and other tools
Approach and Philosophy of On baking technology
Building Integrated photovoltaic BIPV_UPV.pdf
Big Data Technologies - Introduction.pptx
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Network Security Unit 5.pdf for BCA BBA.
KodekX | Application Modernization Development
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Diabetes mellitus diagnosis method based random forest with bat algorithm
Chapter 3 Spatial Domain Image Processing.pdf
Encapsulation theory and applications.pdf
Spectroscopy.pptx food analysis technology

Nginx Scripting - Extending Nginx Functionalities with Lua