Nginx服务之配置文件
纸上得来终觉浅,绝知此事要躬行。


1. 基本特性
Nginx 是一个优秀的 Web、代理、缓存服务器。
基本特性
- 低内存消耗
- 模块化设计,支持模块的动态装卸载(DSO机制)
- 高可靠性,使用master/worker工作模式
- 支持热部署,不停机更新配置文件和程序版本等
- 支持事件驱动、AIO、mmap等机制
基本功能
- 静态资源的Web服务器,能缓存打开的文件描述符
- 支持http、smtp、pop3协议的反向代理、缓存、负载均衡
- 支持FastCGI(fpm)、uWSGI(Python)等
- 模块化、过滤器zip、SSI及图像大小调整等
- 支持SSL安全协议
扩展功能
- 基于名称和IP的虚拟主机
- 支持平滑升级
- 支持路径别名
- 支持URL重写(rewrite)
- 支持keepalive高可用
- 支持基于 IP 及用户的访问控制
- 支持速率限制,支持并发数限制
- 定制访问日志 ,支持使用日志缓冲区提高日志存储性能
基本架构
- 一个master进程,生成一个或多个worker
- 基于事件驱动机制,如epoll、kqueue等
- 支持sendfile、sendfile64的响应机制
- 支持异步IO模型(AIO)
- 支持内存映射机制(mmap)
- 并发收到TCP的套接字限制,最多5万左右,代理的时候更少
防护墙
- 四层防护墙:只针对于流量、IP做过滤
- 七层防火墙:防止爬虫、XSS攻击、请求过滤
2. 安装方法
通过命令行工具安装 Nginx 工具
- (1) 编译环境准备
[[email protected]~]# yum install -y gcc [[email protected]~]# yum install -y make [[email protected]~]# yum groupinstall -y "Development tools" [[email protected]~]# yum install -y pcre-devel [[email protected]~]# yum install -y openssl-develzlib-devel [[email protected]~]# useradd -g nginx -r nginx
- (2) 解压安装
[[email protected]~]# tar xf nginx-1.8.0.tar.gz [[email protected]]# ./configure --prefix=/usr/local/nginx --conf-path=/etc/nginx/nginx.conf --user=nginx --group=nginx --error-log-path=/data/log/nginx/error.log --http-log-path=/data/log/nginx/access.log --pid-path=/var/run/nginx/nginx.pid --lock-path=/var/lock/nginx.lock --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --with-debug [[email protected]]# make && make install
# 生成环境编译配置 1. 为了方便程序迁移可以将配置文件指定到安装目录下或对/etc做定期备份 [[email protected]~]# mkdir -pv /var/tmp/nginx/{client,proxy,fastcgi} [[email protected]]# ./configure --prefix=/usr/local/nginx --conf-path=/etc/nginx/nginx.conf --user=nginx --group=nginx --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx/nginx.pid --lock-path=/var/lock/nginx.lock --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --with-http_flv_module --with-http_mp4_module --http-client-body-temp-path=/var/tmp/nginx/client --http-proxy-temp-path=/var/tmp/nginx/proxy --http-fastcgi-temp-path=/var/tmp/nginx/fastcgi [[email protected]]# make && make install
- (3) 启动服务并检测端口是否启用
[[email protected]~]# /usr/local/nginx/sbin/nginx [[email protected]~]# ss -tnl
3. 模块介绍
Nginx是由内核和模块组成的,内核的设计非常微小和简洁,完成非常简单的工作。仅通过查找配置文件将客户端请求映射到一个location block中,而这个location中所配置的每个指令将会启动不同的模块去完成相应的工作。
Nginx的模块直接被编译进Nginx,因此属于静态编译的方式。启动Nginx后,Nginx的模块被自动加载,不像在Apache一样。首先将模块编译为一个个的so文件,然后在配置文件中指定是否进行加载。在解析配置文件时,Nginx的每一个模块都有可能去处理某个请求,但是同一个处理请求只能由一个模块来完成。 模块分类(层次)
- 核心模块:http模块、event模块、mail模块
- 基础模块:access模块、FastCGI模块、proxy模块、rewrite模块
- 第三方模块:upstream模块、request hash模块、notice模块
模块分类(功能)
- 处理器模块(Handlers):可以直接处理请求并进行内容输出和修改报文信息
- 过滤器模块(Filters):主要对其他处理器模块输出的内容进行修改,最后输出
- 代理类模块(Proxies):主要与后端服务器的交互等操作,如负载均衡和代理
请求处理过程

基本的 Web 服务器请求步骤

第三方模块
- 下面列出的NGINX和NGINX+第三方模块,创建并维护都是NGINX的社区成员,参见官方链接。
模块 | 模块功能表述 | 仓库地址 |
---|---|---|
Accept Language Module | Accept-Language header parser | giom/nginx_accept_language_module |
AFCGI | Asynchronous/multiplexing FastCGI for NGINX | rsms/afcgi |
Akamai G2O | Restricts access to content to Akamai edge servers using G2O headers | kaltura/nginx_mod_akamai_g2o |
Array Var | Add support for array variables to NGINX config files | openresty/array-var-nginx-module |
Audio Track for HTTP Live Streaming | Generate audio track for HTTP Live Streaming (HLS) streams on the fly | flavioribeiro/nginx-audio-track-for-hls-module |
HTTP Digest Authentication | HTTP Digest Authentication | atomx/nginx-http-auth-digest |
PAM Authentication | HTTP Basic Authentication using PAM | sto/ngx_http_auth_pam_module |
Request Authentication | Allows authorization based on subrequest result | ngx_http_auth_request_module |
Auto Lib | Reuse pre-compiled/installed versions of OpenSSL, PCRE and Zlib | simpl/ngx_auto_lib |
AWS Auth | Generate security headers for GET requests to Amazon S3 | anomalizer/ngx_aws_auth |
Backtrace | A NGINX module to dump backtrace case a worker process exits abnormally | alibaba/nginx-backtrace |
Brotli | Serves dynamically or statically compressed responses with brotli | google/ngx_brotli |
Cache Purge | Adds ability to purge content from FastCGI, proxy, and uWSGI caches | FRiCKLE/ngx_cache_purge |
Circle Gif | Generates simple circle images with colors/size specified in the URL | evanmiller/nginx_circle_gif |
Clojure | A module for embedding Clojure, Java, and Groovy programs | nginx-clojure/nginx-clojure |
Concat | Concatenates files in a given context | alibaba/nginx-http-concat |
Upstream Consistent Hash | Select backend based on Consistent hash ring | replay/ngx_http_consistent_hash |
Development Kit | An extension to the core functionality of NGINX | simpl/ngx_devel_kit |
Upstream Domain Resolve | An asynchronous domain name resolve module for NGINX upstream | wdaike/ngx_upstream_jdomain/ |
HTTP Drizzle | Make NGINX talk directly to MySQL or Drizzle database servers | openresty/drizzle-nginx-module |
Dynamic etags | NGINX module for etags on dynamic content | kali/nginx-dynamic-etags |
Dynamic Upstream | Update upstreams’ config by restful interface | yzprofile/ngx_http_dyups_module |
HTTP Echo | Provides familiar shell-style commands to NGINX HTTP servers | openresty/echo-nginx-module |
Stream Echo | Provides familiar shell-style commands to NGINX stream servers | openresty/stream-echo-nginx-module |
Encrypted Session | Encrypt NGINX variables for light-weight session-based authentication | openresty/encrypted-session-nginx-module |
Enhanced Memcached | Repackaging of the standard memcached module to add features | bpaquet/ngx_http_enhanced_memcached_module |
Eval | A module for evaluating memcached or proxy response into variable | vkholodkov/nginx-eval-module |
Eval (OpenResty’s fork) | Captures arbitrary subrequests’ responses into custom NGINX variables | openresty/nginx-eval-module |
Execute | Commands remotely and return results | limithit/NginxExecute |
EY Balancer | Provides a request queue for limiting concurrent requests | ezmobius/nginx-ey-balancer |
Upstream Fair Balancer | Distributes incoming requests to least-busy servers | gnosek/nginx-upstream-fair |
Fancy Index | Like the built-in autoindex module, but fancier | aperezdc/ngx-fancyindex |
Foot Filter | Implements a body filter that adds a given string to the page footer | alibaba/nginx-http-footer-filter |
FastCGI Functional Handler | c/c++ service function handler which built for NGINX fastcgi | Taymindis/fcgi-function |
Footer If Filter | Applies a footer if a response meets a specified condition | flygoast/ngx_http_footer_if_filter/ |
Form Input | Parses HTTP POST request bodies and saves results to NGINX variables | calio/form-input-nginx-module |
GeoIP2 | City and country code lookups via the MaxMind GeoIP2 API | leev/ngx_http_geoip2_module |
GridFS | NGINX module for serving files from MongoDB’s GridFS | mdirolf/nginx-gridfs |
Groovy | A module for embedding Clojure, Java, and Groovy programs | nginx-clojure/nginx-clojure |
Headers More | Set and clear input and output headers… more than “add”! | openresty/headers-more-nginx-module |
HTTP Healthcheck | Health check HTTP servers inside an upstream | cep21/healthcheck_nginx_upstreams |
HTTP Accounting | Realtime netflow and status code monitoring | Lax/ngx_http_accounting_module |
HTTP Iconv | Converts character encodings | calio/iconv-nginx-module |
Internal Redirect | A NGINX module for internal redirection | flygoast/ngx_http_internal_redirect/ |
IP2Location | Identifies the country name/code of an IP address | chrislim2888/ip2location-nginx |
Java | A module for embedding Clojure, Java, and Groovy programs | nginx-clojure/nginx-clojure |
JavaScript | Embedding SpiderMonkey, a full port of Perl module, and more | peter-leonov/ngx_http_js_module#readme |
Upstream Ketama CHash | Provides upstream load distribution by hashing a configurable variable | flygoast/ngx_http_upstream_ketama_chash/releases/ |
LDAP Auth | LDAP module which supports authentication against multiple LDAP servers | kvspb/nginx-auth-ldap |
Limit Upload Rate | Limit the transmission rate of request body from a client | cfsego/limit_upload_rate |
Limit Upstream Connection | Limits the maximum connections to each server in a upstream | cfsego/nginx-limit-upstream/ |
Log If | Log the requests only when given conditions are met | cfsego/ngx_log_if/ |
Log ZMQ | Log the requests via ZeroMQ | alticelabs/nginx-log-zmq |
Lower Upper Case | Provides upper/lowercase string functions in NGINX config files | replay/ngx_http_lower_upper_case |
HTTP Lua | Embed the power of Lua into NGINX HTTP servers (OpenResty Official) | openresty/lua-nginx-module |
Stream Lua | Embed the power of Lua into NGINX TCP servers (OpenResty Official) | openresty/stream-lua-nginx-module |
Luafile | Embed the power of Lua into NGINX | alacner/nginx_lua_module |
HTTP Lua Upstream | Make Nginx http upstream configurations scriptable by Lua | openresty/lua-upstream-nginx-module |
MD5 Filter | Returns the MD5 sum of content that would’ve otherwise been served | kainswor/nginx_md5_filter |
HTTP Memc | Extension of the standard memcached module | openresty/memc-nginx-module |
ModSecurity | Web application firewall | spiderlabs/modsecurity/ |
Mogilefs | Implements a MogileFS client | Download |
Mongo | Upstream module for direct communication with MongoDB | simpl/ngx_mongo |
MP4 Streaming Lite | Seeks time within H.264/MP4 files if a “start” parameter is in the URL | Download |
mruby | Embedded mruby script language for nginx-module | matsumotory/ngx_mruby |
Nchan | Pubsub server for Websockets, Long-Poll, EventSource etc. | slact/nchan |
Naxsi | Web Application Firewall for NGINX | nbs-system/naxsi |
nginx-ip-blocker | An efficient shared memory IP blocking system for nginx. | tmthrgd/nginx-ip-blocker |
Notice | Serve static file to POST requests | kr/nginx-notice |
OCSP proxy | OCSP processing module designed for response caching | kyprizel/nginx_ocsp_proxy-module |
OpenSSL Version | OpenSSL minimum version constraints in configuration | apcera/nginx-openssl-version |
Owner Match | Provides a simple file owner-based access control | Download |
PageSpeed | Rewrites webpages and associated assets to reduce latency and bandwidth | pagespeed/ngx_pagespeed |
PHP | Embedded php script language for nginx-module | rryqszq4/ngx_php |
PHP Session Parser | Extract values that are stored in a serialized PHP session | replay/ngx_http_php_session |
PHP-Memache Standard Hash | Load balancer that imitates the PHP-Memcache standard hash’s behaviour | replay/ngx_http_php_memcache_standard_balancer |
POST authentication | Authentication and authorization via POST request and PAM | veruu/ngx_form_auth |
Postgres | Allows NGINX to communicate directly with PostgreSQL database | Download |
Pubcookie | Adds Pubcookie-based cross-site authentication method to NGINX | ivandeex/pubcookie |
HTTP Push Stream | Turns NGINX into an adept stream HTTP Push server | wandenberg/nginx-push-stream-module |
HTTP rDNS | Makes a reverse DNS lookup and provides control of incoming hostname | flant/nginx-http-rdns |
RDS CSV | Helps ngx_drizzle, ngx_postgres, and others emit Comma-Separated Values | openresty/rds-csv-nginx-module |
RDS JSON | Helps ngx_drizzle, ngx_postgres, and others emit JSON data | openresty/rds-json-nginx-module |
HTTP Redis | Redis support module | Download |
HTTP Redis2 | HTTP Upstream module for the full Redis 2.0 protocol | openresty/redis2-nginx-module |
HTTP Tarantool | HTTP Upstream module for communicate with Tarantool DB | tarantool/nginx_upstream_module |
Replace Filter | Performs regular expression substitutions on response bodies | openresty/replace-filter-nginx-module |
Roboo | HTTP Robot Mitigator that integrates easily with NGINX | yuri-gushin/Roboo/downloads |
RRD Graph | This module provides an HTTP interface to RRDtool’s graphing facilities | evanmiller/mod_rrd_graph |
RTMP | RTMP protocol support. Live streaming and video on demand | arut/nginx-rtmp-module |
RTMPT module | Proxy RTMP packages using stadard HTTP requests | kwojtek/nginx-rtmpt-proxy-module |
Sass | Compiles SASS files in NGINX before sending the response | mneudert/sass-nginx-module |
Secure Download | Create expiring links | replay/ngx_http_secure_download |
Selective Cache Purge | A cache purge module that allows GLOB expressions like .jpg or /test | wandenberg/nginx-selective-cache-purge-module |
Set CConv | Conversion between Simplified and Traditional Chinese at rewrite phase | liseen/set-cconv-nginx-module |
Set Hash | Set a variable to hash functions, including MD5, SHA1 and Murmurhash 2 | simpl/ngx_http_set_hash |
Set Lang | Set a variable to indicate the language based on a variety of sources | simpl/ngx_http_set_lang/downloads |
HTTP Set Misc | Various set_xxx directives added to NGINX’s rewrite module | openresty/set-misc-nginx-module |
sFlow | Operational performance monitoring with standard sFlow protocol | Download |
Shibboleth Auth | Perform authorization based on subrequest to Shibboleth FastCGI app | nginx-shib/nginx-http-shibboleth |
Slice | NGINX module for serving a file in slices (reverse byte-range) | alibaba/nginx-http-slice |
SlowFS Cache | Adds ability to cache static files | Download |
SmallLight | Dynamic Image Transformation Module For NGINX | cubicdaiya/ngx_small_light |
SOCKS | SOCKS5 proxy module for NGINX | dannote/socks-nginx-module |
Sorted Querystring | Expose a variable with the parameters ordered to be used as a cache_key | wandenberg/nginx-sorted-querystring-module |
Sphinx | NGINX upstream module for Sphinx 2.x | reeteshranjan/sphinx2-nginx-module |
SPNEGO | Support for SPNEGO/gssapi in NGINX | stnoonan/spnego-http-auth-nginx-module |
HTTP SRCache | Transparent subrequest-based caching layout for NGINX locations | openresty/srcache-nginx-module |
SSSD info | Retrieves and exposes additional user attributes from SSSD | veruu/ngx_sssd_info |
Static etags | Generates etags for static content | mikewest/nginx-static-etags |
Statsd | Adds the ability for NGINX to interacting with Statsd | zebrafishlabs/nginx-statsd |
Sticky upstream | Adds an upstream server persistance using cookies | nginx-goodies/nginx-sticky-module-ng/get/master.tar.gz |
STS | A stream traffic status module | vozlt/nginx-module-sts |
Subrange | Split one big HTTP/Range request to multiple subrange requesets | Qihoo360/ngx_http_subrange_module |
Substitutions | Performs regular expression and string substitutions on response bodies | yaoweibin/ngx_http_substitutions_filter_module |
Summarizer | An upstream module for Summarizer 1.0 | reeteshranjan/summarizer-nginx-module |
Supervisord | Communicate with supervisord and manage backends on-demand | Download |
Sync Upstreams | Syncing upstreams from etcd or consul, needn’t reload nginx(HTTP Module) | weibocom/nginx-upsync-module |
Sync Upstreams | Syncing upstreams from etcd or consul, needn’t reload nginx(TCP Module) | xiaokai-wang/nginx-stream-upsync-module |
SysGuard | A module to protect the system against too high load | vozlt/nginx-module-sysguard |
TCP Proxy | TCP proxy with NGINX, includes health check and status monitor | yaoweibin/nginx_tcp_proxy_module |
TestCookie module | Simple robot (DDoS) mitigation module | kyprizel/testcookie-nginx-module |
Types Filter | Changes the Content-Type output header on specified conditions | flygoast/ngx_http_types_filter |
UnZip | serve file directly from the archives | youzee/nginx-unzip-module |
Upload | Handles file uploads using multipart/form-data encoding (RFC 1867) | vkholodkov/nginx-upload-module |
NGINX Upload Progress Module | Tracks and reports upload progress | masterzen/nginx-upload-progress-module |
Url | A module to convert uri to user-defined encoding | vozlt/nginx-module-url |
User Agent | A more powerful module than the native BrowserModule | alibaba/nginx-http-user-agent |
Video Thumb Extractor | NGINX module to extract thumbs from a video file | wandenberg/nginx-video-thumbextractor-module |
VOD | Repackage MP4 files for streaming in HLS, HDS, MSS and DASH | kaltura/nginx-vod-module |
VTS | A virtual host and upstream traffic status module | vozlt/nginx-module-vts |
XSS | Native support for cross-site scripting (XSS) | openresty/xss-nginx-module |
Zip | Assemble ZIP archives on the fly | evanmiller/mod_zip |
4. 配置简介
- 配置文件基本结构
main http { upstream { ... } server { listen IP:PORT; location /URL { if ... { ... } root "/path/to/somewhere"; ... } } server { ... } } mail { ... }
- 配置语法格式
- 配置指令要以分号结尾
- directive value1 [value2...];
- 支持使用变量
- 模块内置变量
- 自定义变量set var_name value