SlideShare a Scribd company logo
Nginx Internals [email_address]
Agenda What  Why Architecture Infrastructure Http Module Conf & Location &Static Upstream & fastcgi Extension
What’s Nginx October 4, 2004 6.8% of the top 1 million HTTP Server Reverse proxy server Mail proxy server http://nginx.org/en/
Why Nginx Features : Nginx = transmit + apache Stability : Nginx > Lighttpd Performance : Nginx > Lighttpd > apache Security :  Acess & Limit Zone & Limit Requests Community : sina/qq/tudou/taobao Third party modules more
Code Organization 117590 Core main/lib/data struct Event epool/time/mutex  Http  http server/upstream Os & mail
Architecture Multi-process Master+worker Event driven Non-blocking Single-threaded Highly modular Cache management process
Infrastructure String Array/List/Queue Hash Table Red black tree Memory pool Buff Radix Tree / Slab / Spinlock / shmtx http://code.google.com/p/nginxsrp/wiki/NginxCodeReview
Memory Management ngx_alloc , ngx_calloc , ngx_memalign Memory pool Avoid memory fragmentation and memory leaks Allocation once, deallocation once lifetime : cycle 、 connection 、 Request Optimizing large memory allocation ngx_palloc ngx_pnalloc ngx_pcalloc ngx_pmemalign
Memory pool
Master process
Worker process
Master & woker Socketpair Accept Lock, avoid thundering herd Multi Accept Worker Processes Load-balance (7/8) Connection List per process Timeout handling. Red black tree
Config & command Command-style configuration files, if/echo Configuration block, ‘{}’ Support Include command Support inheritance(Http main/Server/Location) Multi-parameter Variables Conf demo
Config parse Type parse_file parse_block parse_param Command handler
Modular
Http Module http command, http {} ngx_http_block ngx_http_module_t
Http request processing 1 、 phase checker 2 、 phase handler, array 3 、 sub request
http phase NGX_HTTP_POST_READ_PHASE  (realip) NGX_HTTP_SERVER_REWRITE_PHASE  (Rewrite) NGX_HTTP_FIND_CONFIG_PHASE   Can not be extended  NGX_HTTP_REWRITE_PHASE  (Rewite) NGX_HTTP_POST_REWRITE_PHAS E  Can not be extended NGX_HTTP_PREACCESS_PHASE (limit_req 、 limit_zone 、 degradation 、 realip) NGX_HTTP_ACCESS_PHASE (ACCESS  、 auth_basic) NGX_HTTP_POST_ACCESS_PHASE  Can not be extended  NGX_HTTP_TRY_FILES_PHASE  Can not be extended  NGX_HTTP_CONTENT_PHASE  (Autoindex 、 static 、 random_index 、 gzip_static) NGX_HTTP_LOG_PHASE
content phase handler vs content_handler checker: ngx_http_core_content_phase Fastcgi & autoindex
Nginx Filter Header Filter Content Filter ngx_http_send_header ngx_http_output_filter Example  :  gzip 、 more_set_header
Location features Exactly match Regular(sensitive/ insensitive) Location inheritance How to find the right location?
Location internals Ngx_http_block  loc_conf ngx_http_init_locations Location inheritance check ngx_http_init_static_location_trees   Ternary Search Tree(better than trie) Find location(ngx_http_core_find_location)  first static location tree  then regex locations
Static module Sendfile  http://linux.die.net/man/2/sendfile NGX_HTTP_CONTENT_PHASE ngx_http_static_handler ngx_http_static_handler 1 、 method check. GET/HEAD/POST 2 、 Cache processing 3 、  ngx_http_discard_request_body 4 、 output Only Cache fd Red black tree
Nginx Upstream Protocol : Http/Fastcgi/Memcache/SCGI Load-balance: hash/random/round_robin Short connection Long connection only for memcached
Nginx Upstream  :  fastcgi
Extension Develop Core Module Extension, such as nginx-php Http Module Extension Handler :  echo Filter  :  gzip, usertrack upstream :  fastcgi Load-balancers : rand Emiller's Guide To Nginx Module Development
Extension Develop—where? Just before the server reads the config file For every configuration directive for the location and server for which it appears; When Nginx initializes the main configuration When Nginx initializes the server (i.e., host/port) configuration When Nginx merges the server configuration with the main configuration When Nginx initializes the location configuration When Nginx merges the location configuration with its parent server configuration When Nginx's master process starts When a new worker process starts When a worker process exits When the master exits Handling a request Filtering response headers Filtering the response body Picking a backend server Initiating a request to a backend server Re-initiating a request to a backend server Processing the response from a backend server Finishing an interaction with a backend server
Extension Develop—where?
Extension Develop—where?
Extension Develop—where? Http Phase handler Content_handler Header Filter Content Filter
Extension Develop—step “ Config” file ngx_addon_name=ngx_http_baidu_usertrack_module HTTP_AUX_FILTER_MODULES="$HTTP_AUX_FILTER_MODULES ngx_http_baidu_usertrack_module" NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/src/ngx_http_baidu_usertrack_module.c $ngx_addon_dir/src/baidu_des.c" NGX_ADDON_DEPS="$NGX_ADDON_DEPS $ngx_addon_dir/src/baidu_des.h" ORE_LIBS="$CORE_LIBS -lcrypto" Develop and build  ./configure -add-module=path/to/your/new/module/directory Make Make install
Extension Develop—demo Demo
Q&A Q&A Thanks

More Related Content

PPTX
NGINX: Basics and Best Practices
PPTX
5 things you didn't know nginx could do
PPTX
NGINX: Basics & Best Practices - EMEA Broadcast
PDF
NGINX ADC: Basics and Best Practices – EMEA
PPTX
NGINX Installation and Tuning
PPTX
Introduction to NGINX web server
PDF
Nginx Essential
NGINX: Basics and Best Practices
5 things you didn't know nginx could do
NGINX: Basics & Best Practices - EMEA Broadcast
NGINX ADC: Basics and Best Practices – EMEA
NGINX Installation and Tuning
Introduction to NGINX web server
Nginx Essential

What's hot (20)

PPTX
Learn nginx in 90mins
PPTX
Nginx A High Performance Load Balancer, Web Server & Reverse Proxy
PDF
NGINX: Basics and Best Practices EMEA
PPTX
PDF
Nginx Internals
ODP
Introduction to Nginx
PPTX
NGINX: High Performance Load Balancing
PPTX
High Availability Content Caching with NGINX
PDF
gRPC Design and Implementation
PDF
Nginx dhruba mandal
KEY
Web API Basics
PDF
카카오 광고 플랫폼 MSA 적용 사례 및 API Gateway와 인증 구현에 대한 소개
PDF
이벤트 기반 분산 시스템을 향한 여정
PPTX
node.js.pptx
PDF
Docker Introduction
PDF
Rest in flask
PPTX
What is gRPC introduction gRPC Explained
PPTX
Introduction to Node.js
PPTX
Load Balancing and Scaling with NGINX
PPTX
HTTP request and response
Learn nginx in 90mins
Nginx A High Performance Load Balancer, Web Server & Reverse Proxy
NGINX: Basics and Best Practices EMEA
Nginx Internals
Introduction to Nginx
NGINX: High Performance Load Balancing
High Availability Content Caching with NGINX
gRPC Design and Implementation
Nginx dhruba mandal
Web API Basics
카카오 광고 플랫폼 MSA 적용 사례 및 API Gateway와 인증 구현에 대한 소개
이벤트 기반 분산 시스템을 향한 여정
node.js.pptx
Docker Introduction
Rest in flask
What is gRPC introduction gRPC Explained
Introduction to Node.js
Load Balancing and Scaling with NGINX
HTTP request and response
Ad

Similar to Nginx internals (20)

ODP
IT Operations for Web Developers
PDF
Running php on nginx
PDF
Nginx + PHP
PDF
ITB2019 NGINX Overview and Technical Aspects - Kevin Jones
PDF
ITB2017 - Nginx Effective High Availability Content Caching
PDF
High Availability Content Caching with NGINX
PDF
Using NGINX as an Effective and Highly Available Content Cache
DOCX
How to install and configure LEMP stack
PDF
Load Balancing Applications with NGINX in a CoreOS Cluster
PDF
Nginx pres
PPT
Oscon 2010 - ATS
PDF
Socket programming, and openresty
PPTX
5 things you didn't know nginx could do velocity
PPT
WE18_Performance_Up.ppt
KEY
Using Apache as an Application Server
PDF
ApacheConNA 2015: What's new in Apache httpd 2.4
PPTX
ASP.NET WEB API Training
ODP
Caching and tuning fun for high scalability
PDF
Deploying nginx with minimal system resources
PPTX
Everything you wanted to know about writing async, concurrent http apps in java
IT Operations for Web Developers
Running php on nginx
Nginx + PHP
ITB2019 NGINX Overview and Technical Aspects - Kevin Jones
ITB2017 - Nginx Effective High Availability Content Caching
High Availability Content Caching with NGINX
Using NGINX as an Effective and Highly Available Content Cache
How to install and configure LEMP stack
Load Balancing Applications with NGINX in a CoreOS Cluster
Nginx pres
Oscon 2010 - ATS
Socket programming, and openresty
5 things you didn't know nginx could do velocity
WE18_Performance_Up.ppt
Using Apache as an Application Server
ApacheConNA 2015: What's new in Apache httpd 2.4
ASP.NET WEB API Training
Caching and tuning fun for high scalability
Deploying nginx with minimal system resources
Everything you wanted to know about writing async, concurrent http apps in java
Ad

More from liqiang xu (12)

PDF
浅谈灰度发布在贴吧的应用 支付宝 20130909
PDF
Csrf攻击原理及防御措施
PDF
Hdfs comics
PDF
Xldb2011 wed 1415_andrew_lamb-buildingblocks
PDF
Xldb2011 tue 1055_tom_fastner
PDF
Xldb2011 tue 1005_linked_in
PDF
Xldb2011 tue 0940_facebook_realtimeanalytics
PDF
Xldb2011 tue 1120_youtube_datawarehouse
PDF
Selenium私房菜(新手入门教程)
PDF
大话Php之性能
PPT
1.4亿在线背后的故事(2)
PPT
1.4亿在线背后的故事(1)
浅谈灰度发布在贴吧的应用 支付宝 20130909
Csrf攻击原理及防御措施
Hdfs comics
Xldb2011 wed 1415_andrew_lamb-buildingblocks
Xldb2011 tue 1055_tom_fastner
Xldb2011 tue 1005_linked_in
Xldb2011 tue 0940_facebook_realtimeanalytics
Xldb2011 tue 1120_youtube_datawarehouse
Selenium私房菜(新手入门教程)
大话Php之性能
1.4亿在线背后的故事(2)
1.4亿在线背后的故事(1)

Recently uploaded (20)

PDF
Approach and Philosophy of On baking technology
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
cuic standard and advanced reporting.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Machine learning based COVID-19 study performance prediction
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
A Presentation on Artificial Intelligence
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
KodekX | Application Modernization Development
Approach and Philosophy of On baking technology
Empathic Computing: Creating Shared Understanding
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
cuic standard and advanced reporting.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
The Rise and Fall of 3GPP – Time for a Sabbatical?
Machine learning based COVID-19 study performance prediction
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Network Security Unit 5.pdf for BCA BBA.
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
A Presentation on Artificial Intelligence
Digital-Transformation-Roadmap-for-Companies.pptx
20250228 LYD VKU AI Blended-Learning.pptx
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
KodekX | Application Modernization Development

Nginx internals

  • 2. Agenda What Why Architecture Infrastructure Http Module Conf & Location &Static Upstream & fastcgi Extension
  • 3. What’s Nginx October 4, 2004 6.8% of the top 1 million HTTP Server Reverse proxy server Mail proxy server http://nginx.org/en/
  • 4. Why Nginx Features : Nginx = transmit + apache Stability : Nginx > Lighttpd Performance : Nginx > Lighttpd > apache Security : Acess & Limit Zone & Limit Requests Community : sina/qq/tudou/taobao Third party modules more
  • 5. Code Organization 117590 Core main/lib/data struct Event epool/time/mutex Http http server/upstream Os & mail
  • 6. Architecture Multi-process Master+worker Event driven Non-blocking Single-threaded Highly modular Cache management process
  • 7. Infrastructure String Array/List/Queue Hash Table Red black tree Memory pool Buff Radix Tree / Slab / Spinlock / shmtx http://code.google.com/p/nginxsrp/wiki/NginxCodeReview
  • 8. Memory Management ngx_alloc , ngx_calloc , ngx_memalign Memory pool Avoid memory fragmentation and memory leaks Allocation once, deallocation once lifetime : cycle 、 connection 、 Request Optimizing large memory allocation ngx_palloc ngx_pnalloc ngx_pcalloc ngx_pmemalign
  • 12. Master & woker Socketpair Accept Lock, avoid thundering herd Multi Accept Worker Processes Load-balance (7/8) Connection List per process Timeout handling. Red black tree
  • 13. Config & command Command-style configuration files, if/echo Configuration block, ‘{}’ Support Include command Support inheritance(Http main/Server/Location) Multi-parameter Variables Conf demo
  • 14. Config parse Type parse_file parse_block parse_param Command handler
  • 16. Http Module http command, http {} ngx_http_block ngx_http_module_t
  • 17. Http request processing 1 、 phase checker 2 、 phase handler, array 3 、 sub request
  • 18. http phase NGX_HTTP_POST_READ_PHASE (realip) NGX_HTTP_SERVER_REWRITE_PHASE (Rewrite) NGX_HTTP_FIND_CONFIG_PHASE Can not be extended NGX_HTTP_REWRITE_PHASE (Rewite) NGX_HTTP_POST_REWRITE_PHAS E Can not be extended NGX_HTTP_PREACCESS_PHASE (limit_req 、 limit_zone 、 degradation 、 realip) NGX_HTTP_ACCESS_PHASE (ACCESS 、 auth_basic) NGX_HTTP_POST_ACCESS_PHASE Can not be extended NGX_HTTP_TRY_FILES_PHASE Can not be extended NGX_HTTP_CONTENT_PHASE (Autoindex 、 static 、 random_index 、 gzip_static) NGX_HTTP_LOG_PHASE
  • 19. content phase handler vs content_handler checker: ngx_http_core_content_phase Fastcgi & autoindex
  • 20. Nginx Filter Header Filter Content Filter ngx_http_send_header ngx_http_output_filter Example : gzip 、 more_set_header
  • 21. Location features Exactly match Regular(sensitive/ insensitive) Location inheritance How to find the right location?
  • 22. Location internals Ngx_http_block loc_conf ngx_http_init_locations Location inheritance check ngx_http_init_static_location_trees Ternary Search Tree(better than trie) Find location(ngx_http_core_find_location) first static location tree then regex locations
  • 23. Static module Sendfile http://linux.die.net/man/2/sendfile NGX_HTTP_CONTENT_PHASE ngx_http_static_handler ngx_http_static_handler 1 、 method check. GET/HEAD/POST 2 、 Cache processing 3 、 ngx_http_discard_request_body 4 、 output Only Cache fd Red black tree
  • 24. Nginx Upstream Protocol : Http/Fastcgi/Memcache/SCGI Load-balance: hash/random/round_robin Short connection Long connection only for memcached
  • 25. Nginx Upstream : fastcgi
  • 26. Extension Develop Core Module Extension, such as nginx-php Http Module Extension Handler : echo Filter : gzip, usertrack upstream : fastcgi Load-balancers : rand Emiller's Guide To Nginx Module Development
  • 27. Extension Develop—where? Just before the server reads the config file For every configuration directive for the location and server for which it appears; When Nginx initializes the main configuration When Nginx initializes the server (i.e., host/port) configuration When Nginx merges the server configuration with the main configuration When Nginx initializes the location configuration When Nginx merges the location configuration with its parent server configuration When Nginx's master process starts When a new worker process starts When a worker process exits When the master exits Handling a request Filtering response headers Filtering the response body Picking a backend server Initiating a request to a backend server Re-initiating a request to a backend server Processing the response from a backend server Finishing an interaction with a backend server
  • 30. Extension Develop—where? Http Phase handler Content_handler Header Filter Content Filter
  • 31. Extension Develop—step “ Config” file ngx_addon_name=ngx_http_baidu_usertrack_module HTTP_AUX_FILTER_MODULES="$HTTP_AUX_FILTER_MODULES ngx_http_baidu_usertrack_module" NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/src/ngx_http_baidu_usertrack_module.c $ngx_addon_dir/src/baidu_des.c" NGX_ADDON_DEPS="$NGX_ADDON_DEPS $ngx_addon_dir/src/baidu_des.h" ORE_LIBS="$CORE_LIBS -lcrypto" Develop and build ./configure -add-module=path/to/your/new/module/directory Make Make install