文档库 最新最全的文档下载
当前位置:文档库 › Nginx模块开发文档

Nginx模块开发文档

Nginx模块开发文档
Nginx模块开发文档

nginx文档

吴东

April 28, 2009

Contents

1前言5

2基本配置7

2.1安装 (7)

2.2配置说明 (10)

2.3启动和控制 (25)

3深入源码27

3.1源码结构 (27)

3.2configure配置 (27)

3.3nginx源码习惯 (27)

3.4常用基础库 (28)

3.5core模块 (40)

3.6event模块 (44)

3.7http模块 (46)

4模块编写55

4.1http模块编写 (55)

4.2基于nginx的高性能服务器开发. . . . . . . . . 55

5附录57

5.1编译器参数 (57)

5.2系统函数 (59)

CONTENTS CONTENTS

Chapter 1

前言

在互联网编程中,http服务器编程作为一个非常重要方向一直为各种语言所重视,从c语言的apache,Lighttpd到当前非常流行的nginx。Java有tom-cat,jetty,websphere等众多服务器,pyhoen的zope等服务器。既有重量级的服务器,又有轻量级的,嵌入式的服务器。从互联网的应用来说,c语言的http 服务器一直占有主导地位,当前最流行的三个开源服务器有apache,Lighttpd和nginx。Apache作为经典的Web服务器,除了慢没有别的缺点了,Apache2对fcgi支持并不好,非常好用的proxy和proxy_ajp (很多人用它作为tomcat的前端),不支持epoll(这年头,epoll几乎是性能的必备)。Lighttpd作为杀手级的静态文件能力,杀手级的fcgi能力但是proxy模块不够稳定。Nginx速度快,占用资源少,杀手级的proxy和rewrite,非常不错的静态文件能力,最适合作为整个网站的前端服务(将php、svn等不同请求发送往后端apache)。现在国内Nginx的用户越来越多了,多数拥抱Nginx的网站都钟意其优异的性能表现,如果是相对比较大的网站,节约下来的服务器成本无疑是客观的。当前Ngnix美中不足之处是相关的文档和用户经验都还是很欠缺,用户之间还很难做到可借鉴性的交流。最近因为朋友遇到一些技术问题,我也翻阅了不少Nginx的邮件列表内容,发现大量的技术细节仍然在频繁变化中,可是中文社区内相关的记录和讨论太少了。相信国内这些Nginx用户积攒的经验肯定是不少的,但可能是因为某些其它因素考虑而看不到相关的技术分享。本书的写作就是为了向大家展示nginx的内部结构,以便于大家更好的使用该服务器。对于一个八万行代码的http服务器,从性能来看它是那么的出色,从功能

来看它并不逊色于几十万行的apache服务器。Nginx是实现有几个非常出色的地方:模块化设计,流水线请求处理,多进程控制,epoll的使用,平滑的升级程序或是配置文件。Nginx采用的是单线程的方式,网络服务器的几种模型可以参考C10K的介绍。当然,如果在linux下,最好的模型自然是EPool (effectiveepoll?)。目前一台服务器支持10K个客户访问,基本上还比较麻烦,64位的CPU,可能是一个比较好的解决方案。2块1000M网卡,10K客户端,每个客户端的带宽是2000/10000=200K,这是理论值,勉强可行。考虑一下纯粹的线程模型。10K个客户端,需要10K个线程。考虑到每个进程3G 的用户空间,那么每个线程的空间是3000M/10K=300K,只能说非常勉强可以运行(每个线程的cruntime大约需要2-3K空间)。但是大量的线程调度会极大的减缓系统效率。再考虑一下多个进程的模型,每个进程创建多个线程。其实与纯粹的线程模型差异不大,不过是每个线程的用户空间不受太大限制。大量的线程调度带来的巨大性能损耗会使得整个系统效率及其低下。当然,这种模型也不是一无是处,对于客户端数目不多的情况,比如ftp服务器,这种模型是非常合适的。然后就剩下epoll模Chapter1.前言

型。要使用epoll模型,首先必须有Linux2.6的内核。了解select模型的人都知道,select每个句柄只能支持64个socket,这可以通过阅读linuxselect.h知道。而Poll模型则是一种事件触发的模型,没有64个socket的限制。epoll是对Poll模型的一个改造,让一个Poll句柄可以同时支持多个Socket句柄,好处是将大量Poll句柄的事件探测机制放到内核中处理,大大减少了将数据从内核态拷贝到用户态的次数,从而提高效率。阅读Linux的源码可以看到,epoll的内部使用的是一个Hashmap,Hashmap中存放Poll对象,所以从根本上来说,epoll模型是一种更好的Poll模型(我一直理解为EffectivePoll)。

当然nginx也有不足的地方,例如各个模块之间的耦合性太强,各个模块不适合直接拿出来使用。Nginx 的作者过于强调按照他自己所理解的模块化,而把一些基础模块也用作者所谓的模块化来实现,导致代码相互引用太多,艰涩难懂。

本书的编写的面向的用户除了初级linux工程师外,还可以为中高级linux工程师作为开发高性能服务器的工具书,目的除了向用户展示nginx精巧的设计和完整的实现外,还希望通过本书的讲解能够让用户以nginx作为基本框架或是自己实现更多的高性能服务器。

Chapter 2

基本配置

2.1安装

安装依赖模块

1.

gzip模块需要zlib库,该模块在https://www.wendangku.net/doc/b54999586.html,/网站下载。

2.

rewrite模块需要pcre库,该模块在https://www.wendangku.net/doc/b54999586.html,/网站下载。

3.

ssl功能需要openssl库该模块在https://www.wendangku.net/doc/b54999586.html,/网站下载。

官方源代码下载

在http://sysoev.ru/nginx/download.html网站上可以下载nginx源代码。

使用源代码安装

Nginx使用Unix下常用的?./configure && make && make install‘过程来编译安装。configure脚本确定系统所具有一些特性,特别是nginx用来处理连接的方法。然后,它创建Makefile文件。configure支持下面的选项:

–prefix=

-Nginx安装路径。如果没有指定,默认为/usr/local/nginx。

–sbin-path=

-Nginx可执行文件安装路径。只能安装时指定,如果没有指定,默认为

/sbin/nginx。

–conf-path=

-在没有给定-c选项下默认的nginx.conf的路径。如果没有指定,默认为

/conf/nginx.conf。

–pid-path=

-在nginx.conf中没有指定pid指令的情况下,默认的nginx.pid的路径。如果没有指定,默认为

/logs/nginx.pid。

–lock-path=

-nginx.lock文件的路径。

–error-log-path=

-在nginx.conf中没有指定error_log指令的情

2.1.安装Chapter2.基本配置

况下,默认的错误日志的路径。如果没有指定,默认为

/logs/er-ror.log。

–http-log-path=

-在nginx.conf中没有指定access_log指令的情况下,默认的访问日志的路径。如果没有指定,默认为

/logs/ac-cess.log。

–user=-在nginx.conf中没有指定user指令的情况下,默认的nginx使用的用户。如果没有指定,默认为nobody。–group=-在nginx.conf中没有指定user指令的情况下,默认的nginx使用的组。如果没有指定,默认为nobody。–builddir=DIR-指定编译的目录–with-rtsig_module-启用rtsig模块

–with-select_module–without-select_module-允许或不允许开启SE-LECT模式,如果configure没有找到更合适的模式,比如:kqueue(sun os),epoll (linux kenel2.6+), rtsig(实时信号)或者/dev/poll(一种类似select的模式,底层实现与SELECT基本相同,都是采用轮训方法) SELECT模式将是默认安装模式

–with-poll_module –without-poll_module -允许或不允许开启pool模式.–with-http_ssl_module-开启HTTPSSL模块,使NGINX可以支持HTTPS请求。这个模块需要已经安装了OPENSSL,在DEBIAN 上是libssl–with-http_realip_module-启用ngx_http_realip_module。–with-http_addition_module-启用ngx_http_addition_module–with-http_sub_module-启用ngx_http_sub_module–with-http_dav_module-启用ngx_http_dav_module–with-http_flv_module-启用ngx_http_flv_module –with-http_stub_status_module -启用―server status‖页–without-http_charset_module -禁用ngx_http_charset_module –without-http_gzip_module -禁用ngx_http_gzip_module.如果启用,需要zlib。–without-http_ssi_module -禁用ngx_http_ssi_module–without-http_userid_module-禁用ngx_http_userid_module–without-http_access_module-禁用ngx_http_access_module–without- http_auth_basic_module-禁用ngx_http_auth_basic_module–without- http_autoindex_module-禁用ngx_http_autoindex_module–without- http_geo_module-禁用ngx_http_geo_module–without-http_map_module-禁用ngx_http_map_module–without-http_referer_module-禁用ngx_http_referer_module–without-http_rewrite_module-禁用ngx_http_rewrite_module.如果启用需要PCRE。–without-http_proxy_module-禁用ngx_http_proxy_module

Chapter2.基本配置2.1.安装

–without-http_fastcgi_module-禁用ngx_http_fastcgi_module–without- http_memcached_module-禁用ngx_http_memcached_module–without- http_limit_zone_module-禁用ngx_http_limit_zone_module–without- http_empty_gif_module-禁用ngx_http_empty_gif_module–without- http_browser_module-禁用ngx_http_browser_module–without-http_upstream_ip_hash_module-禁用ngx_http_upstream_ip_hash_module–with-http_perl_module-启用ngx_http_perl_module

–with-perl_modules_path=PATH-指定perl模块的路径–with-perl=PATH

-指定perl执行文件的路径–http-log-path=PA TH -Set path to the http access log –http-client-body-temp-path=PATH -Set path to the http client

request body temporary files –http-proxy-temp-path=PATH -Set path to the http proxy temporary files –http-fastcgi-temp-path=PA TH -Set path to the http fastcgi tem-

porary files –without-http -禁用HTTP server –with-mail -启用IMAP4/POP3/SMTP代理模块–with-mail_ssl_module -启用ngx_mail_ssl_module –with-cc=PATH -指定C编译器的路径–with-cpp=PATH -指定C预

处理器的路径–with-cc-opt=OPTIONS -Additional parameters which will be added to the variable CFLAGS. With the use of the system library PCRE in FreeBSD, it is necessary to indicate –with-cc-opt=‖-I /usr/local/include‖. If we are using select() and it is neces sary to increase the number of file descriptors, then

this also can be assigned here: –with-cc-opt=‖-D FD_SETSIZE=2048″. –with-ld-opt=OPTIONS -Additional parameters passed to the linker.

With the use of the system library PCRE in FreeBSD, it is necessary to indicate –with-ld-opt=‖-L /usr/local/lib‖.–with-cpu-opt=CPU -为特定的CPU编译,有效的值包括:pentium, pentiumpro, pentium3, pentium4, athlon, opteron, amd64, sparc32, sparc64, ppc64

–without-pcre -禁止PCRE库的使用。同时也会禁止HTTP rewrite模块。在―location‖配置指令中的正则表达式也需要PCRE。–with-pcre=DIR -指定PCRE库的源代码的路径。–with-pcre-opt=OPTIONS -Set additional options for PCRE building. –with-md5=DIR -Set path to md5 library sources.

2.2.配置说明Chapter2.基本配置

–with-md5-opt=OPTIONS -Set additional options for md5 building.

–with-md5-asm -Use md5 assembler sources.

–with-sha1=DIR -Set path to sha1 library sources.

–with-sha1-opt=OPTIONS -Set additional options for sha1 building.

–with-sha1-asm -Use sha1 assembler sources.

–with-zlib=DIR -Set path to zlib library sources.

–with-zlib-opt=OPTIONS -Set additional options for zlib building.

–with-zlib-asm=CPU -Use zlib assembler sources optimized for

specified CPU, valid values are: pentium, pentiumpro –with-openssl=DIR -Set path to OpenSSL library sources –with-openssl-opt=OPTIONS -Set additional options for OpenSSL

building –with-debug -启用调试日志–add-module=PATH -Add in a third-party module found in directory PATH在不同版本间,选项可能会有些许变化,请总是使用./configure–help命令来检查一下当前的选项列表。示例(最好能在同一行):

1 ./ configure \

2 ..sbin.path =/ usr / local / nginx / nginx \

3 ..conf.path =/ usr / local / nginx / nginx . conf \

4 ..pid.path =/ usr / local / nginx / nginx . pid \

5 ..with.http_ssl_module \

6 ..with.pcre =../ pcre .4.4 \

7 ..with.zlib =../ zlib .1.1.3

Example on Ubuntu/debian with libgcrypt11-dev, libpcre3-dev and libssl-dev installed (choose EITHER –with-md5 OR –with-sha1, but not both; on debian and ubuntu, they should both point to /usr/lib)

1 ./ configure \

2 ..with.openssl =/ usr / lib / ssl / \

3 ..with.md5 =/ usr / lib

An Ubuntu Edgy .deb for version 0.5.2 can be found here: nginx_0.5.2-1_i386.deb. (NOTE: According to an October 2006 message md5 was used in a now broken http cache module and sha1 is used in an incomplete mysql library module and so are currently not needed.)

2.2配置说明

主模块

daemon

Chapter2.基本配置2.2.配置说明

语法: daemon on | off

缺省值: on生产环境中不要使用‖daemon‖和‖master_process‖指令,这

些选项仅用于开发调试。

debug_points

语法: debug_points [stop | abort]

缺省值: nonedebug_points stop;应该适用于调试,在调试器内设置断

点之类的。

error_log

语法: error_log file [ debug | info | notice | warn | error | crit

]

缺省值: ${prefix}/logs/error.log Nginx添加–with-debug编译参数,你还能够使用以下配置: error_log LOGFILE [ debug_core | debug_alloc

| debug_mutex | debug_event | debug_http | debug_imap];

include

语法:include file | *

缺省值: none你可以在任意地方使用include指令实现配置文件的包含,类似于apache中的include方法,可减少主配置文件d。include指令还支持像下面配置一样的全局包含的方法,例如包含一个目录下所有以‖.conf‖结尾的文件:include vhosts/*.conf;注意路径受到configure编译参数–prefix=<路径>指令的影响,如果没有指定,Nginx默认是被编译在/usr/local/nginx。

lock_file

语法: lock_file file

缺省值: compile-time option lock_file /var/log/lock_file; nginx uses accept mutex to serialize accept() syscalls. If nginx is built by gcc, Intel C++, or SunPro C++ compilers on i386, amd64, sparc64, and ppc64, then nginx uses the atomic instructions to implement the mutex. In other cases the lock file would be used.

master_process

语法: master_process on | off

缺省值:on master_process off;生产环境中不要使用‖daemon‖和‖master_process‖指

令,这些选项仅用于开发调试。

pid

语法: pid file

缺省值:compile-time option Example:pid /var/log/nginx.pid;进程

id存储文件。可以使用kill -HUP cat/var/log/nginx.pid\对Nginx进行配置文件重新加载。

SSL_ENGINE

语法: ssl_engine engine

缺省值: system dependent该指令用于指定openssl使用的引擎。你可以通过下面的命令行获知系统目前支

持的openssl引擎openssl engine -t例如: $ openssl engine -t (cryptodev) BSD cryptodev engine [ available 2.2.配置说明Chapter2.基本配置

] (dynamic) Dynamic engine loading support [ unavailable ]

timer_resolution

语法: timer_resolution t

缺省值: none Example: timer_resolution 100ms; The directive al-lows to decrease number gettimeofday() syscalls.By缺省值gettime-ofday() is called after each return from kevent(), epoll, /dev/poll, select(), poll(). But if you need an exact time in logs when log-ging $upstream_response_time, or $msec variables, then you should use timer_resolution.

USER

语法: user user [group]

缺省值:nobody nobody指定Nginx Worker进程运行用户,默认是nobody帐号。例如: user www users; worker_cpu_affinity

语法: worker_cpu_affinity cpumask [cpumask...]

缺省值: none Linux only. With this option you can bind the worker process to a CPU, it calls sched_setaffinity().仅适用于linux,使用该选项可以绑定worker进程和CPU. For example, worker_proceses 4; worker_cpu_affinity 555-5555 555-5555; Bind each worker process to one CPU only.分别给每个worker进程绑定一个CPU. worker_proceses 2; worker_cpu_affinity 555-5555; Bind the first worker to CPU0/CPU2, bind the second worker to CPU1/CPU3.This is suitable for HTT.将CPU0/CPU2绑定给第一个worker进程,将CPU1/CPU3绑定给第二个worker进程。

worker_priority

语法: worker_priority [-]number

缺省值: on With this option you can give to all worker processes the priority (nice) you need/wish, it calls setpriority().使用该选项可以给所有的worker进程分配优先值。

worker_processes

语法: worker_processes number

缺省值: 1 e.g.: worker_processes 5; nginx has the ability to use more than one worker process for several reasons:nginx可以使用多个worker进程,原因如下:to use SMP to decrease latency when workers blockend on disk I/O to limit number of connections per process when select()/poll() is used The worker_processes and worker_connections from the event sections allows you to calculate maxclients value: k max_clients = worker_processes * worker_connections

worker_rlimit_core

语法: worker_rlimit_core size

缺省值: ? Maximum size of core file per worker;

worker_rlimit_nofile

语法: worker_rlimit_nofile limit

Chapter2.基本配置2.2.配置说明

缺省值: ? Specifies the value for maximum file descriptors that can be opened by this process.指定

worker_rlimit_sigpending

语法: worker_rlimit_sigpending limit

缺省值: ? (Since Linux 2.6.8) Specif ies the limit on the number of signals that may be queued for the real user ID of the calling process.

working_directory

语法: working_directory path

缺省值: –prefix This is the working directory for the workers. It‘s used for core files only. nginx uses absolu te paths only, all relative paths in configuration files are relative to –prefix==PA TH.

event配置

http参数

alias

语法: alias file-path|directory-path;

缺省值: no context: location This directive assigns a path to be used for the indicated location. Note that it may look similar to the root directive, but the document root doesn‘t change, just the file system path used for the request. For example:

1 location /i/ {

2 alias / spool / w

3 / images /;

3 }

The request ―/i/top.gif‖ will return the file ―/spool/w3/images/ top.gif‖. It is possible to use variables in the replacement path. The alias directive cannot be used inside a regex-specified location. If you need to do this you must use a combination of rewrite and root.

client_body_in_file_only

语法: client_body_in_file_only on|off

缺省值: client_body_in_file_only off context: http, server, lo-cation The directive enables to store a client request body in a file. Please note that the file at the request completion will not be removed if the directive is enabled. The directive can be used for debugging and for the $r->request_body_file method in the ngx_http_perl_module module.

client_body_buffer_size

语法: client_body_buffer_size the_size

缺省值: client_body_buffer_size 8k/16k context: http, server, location The directive specifies the client request body buffer size. If the request body is more than the buffer, then the entire request

2.2.配置说明Chapter2.基本配置

body or some part is written in a temporary file.The缺省值size is equal to two pages size, depending on platform it is either 8K or 16K.

client_body_temp_path

语法: client_body_temp_path dir-path [ level1 [ level2 [ level3 ] ]]

缺省值: client_body_temp_path client_body_temp context: http, server, location The directive assigns the directory for storing the temporary files in it with the body of the request. In the dir-path a hierarchy of subdirectories up to three levels are possible. For example

1 client_body_temp_path /spool/nginx/client_temp 1 2;

The directory structure will be like this: /spool/nginx/client_temp/ 7/45/555-55557

client_body_timeout

语法: client_body_timeout time

缺省值: client_body_timeout 60 context: http, server, location Directive sets the read timeout for the request body from client. The timeout is set only if a body is not get in one readstep. If after this time the client send nothing, nginx returns error ―Request time out‖ (408).

client_header_buffer_size

语法: client_header_buffer_size size

缺省值: client_header_buffer_size 1k context: http, server Direc-tive sets the headerbuffer size for the request header from client. For the overwhelming majority of requests it is completely sufficient a buffer size of 1K.

However if a big cookie is in the request-header or the request has come from a wap-client the header can not be placed in 1K, therefore, the request-header or a line of request-header is not located completely in this buffer nginx allocate a bigger buffer, the size of the bigger buffer can be set with the instruction large_client_header_buffers.

client_header_timeout

语法: client_header_timeout time

缺省值: client_header_timeout 60 context: http, server Directive assigns timeout with reading of the title of the request of client. The timeout is set only if a header is not get in one readstep. If after this time the client send nothing, nginx returns error ―Request time out‖ (408).

client_max_body_size

语法: client_max_body_size size

缺省值: client_max_body_size 1m context: http, server, location Directive assigns the maximum accepted body size of client request,

Chapter2.基本配置2.2.配置说明

indicated by the line ―Content-Length‖ in the header of request. If size is greater the given one, then the client gets the error ―Request Entity Too Large‖ (413). It is necessary to keep in mind that the browsers do not know how to correctly show this error.

缺省值_type

语法:缺省值_type MIME-type

缺省值:缺省值_type text/plain context: http, server, location default_type assigns the default MIME-type to be used for files where the standard MIME map doesn‘t specify anything. See also types Example:

1 location = / proxy . pac {

2 default_type application /x.ns.proxy.autoconfig ;

3 }

4 location = / wpad . dat {

5 rewrite . / proxy . pac ;

6 default_type application /x.ns.proxy.autoconfig ;

7 }

error_page

语法: error_page code [ code... ] [ = |=answer-code ] uri

缺省值: no context: http, server, location, if in location The directive specifies the URI, which will be showed for the errors indicated. Example of the use:

1 error_page 404 /404.html;

2 error_page 502 50

3 50

4 /50x.html;

3 error_page 403 https://www.wendangku.net/doc/b54999586.html,/forbidden.html;

Furthermore, it is possible to change the code of answer to another, for example: error_page 404 =200 /.empty.gif; If an erroneous answer is processed by the proxied or FastCGI server and this server can return the different answer codes, for example, 200, 302, 401 or 404, then it is possible to issue the code returned: error_page 404 = / 404.php;

index

语法: index file [file...]

缺省值: index index.html context: http, server, location Directive determines the file(s) which will be used as the index. I t‘s possible to use variables in the name of file. The presence of the files is checked in the order of their enumeration. A file with an absolute path can be put at the end. Example using a variable: index index. $geo.html

index.0.html /index.html;

internal

语法: internal

缺省值: no context: location internal indicates that the match-ing location can be used only for so called ―internal‖ requests. For

2.2.配置说明Chapter2.基本配置

external requests it will return the error ―Not found‖ (404). Inter-nal requests are the following: requests redirected by the instruc-tion error_page subrequests created by the command include virtual of the ―ngx_http_ssi_module‖ module requests changed by the instruction rewrite of the ―ngx_http_rewrite_module‖ module An example to prevent clients fetching error pages directly:

1 error_page 404 /404.html;

2 location /404.html {

3

internal; 4}

keepalive_timeout

语法: keepalive_timeout time [ time ]

缺省值: keepalive_timeout 75 context: http, server, location Directive assigns the timeout, for keep-alive connections with the client. The second parameter assigns value in the line ―Keep-Alive: timeout=time‖ in the header of answer. The parameters can differ from each other. Line ―Keep-Alive: timeout=time‖ understands Mozilla and Konqueror. MSIE itself shuts keep-alive connection approximately after 60 seconds.

large_client_header_buffers

语法: large_client_header_buffers number size

缺省值: large_client_header_buffers 4 4k/8k context: http, server Directive assigns the maximum number and size of buffers for large headers to read from client request. The request line can not be bigger then the size of one buffer, if the client send a bigger header nginx returns error ―Request URI too large‖ (414). The longest header line of request also must be not more than the size of one buffer, otherwise the client get the error ―Bad request‖ (400). Buffers are separated only as needed. By default the size of one buffer is equal to the size of page, depending on platform this either 4K or 8K, if at the end of working request connection converts to state keep-alive, then these buffers are freed.

limit_except

语法: limit_except methods {…}

缺省值: no context: location Directive limits HTTP-methods, acces-sible inside location. For the limitation can be used the directives of modules ngx_http_access_module and ngx_http_auth_basic_module: limit_except GET { allow 192.168.1.0/32; deny all; }

limit_rate

语法: limit_rate speed

缺省值: no context: http, server, location, if in location Direc-tive assigns the speed of transmission of the answer to client. Speed is assigned in the bytes per second. Limitation works only for one connection, i.e., if client opens 2 connections, then total velocity

Chapter2.基本配置2.2.配置说明

will be 2 times than higher limited. If it is necessary to limit speed for the part of the clients at the level of server, then directive limit_rate for this does not be suitable. Instead of this should be assigned the necessary speed of variable $limit_rate:

1 2 3 4 server if } { ( $slow ) { set $limit_rate 4k;

5

6 …

7 8 }

listen

语法:listen address:port [缺省值[ backlog=num | rcvbuf=size | sndbuf=size | accept_filter=filter | deferred | bind ] ]

缺省值: listen 80 context: server The directive specifies the address and port, on which the server accepts requests. It is possible to specify address or port only, besides, an address can be the server name, for example:

1 listen 127.0.0.1:8000;

2 listen 127.0.0.1;

3 listen 8000;

4 listen *:8000;

5 listen localhost :8000;

If only address is given, then缺省值port 80 is used. If the directive has the‖缺省值‖ parameter, then the server, in whom is described this directive, he will be the缺省值server for the ad-dress:port pair, but if there are no directives with the‖缺省值‖parameter, then the缺省值server will be the first server, in whom is described the address:port pair. In directive listen with parameter缺省值it is possible to indicate several parameters, specific for the system calls listen(2) and bind(2). backlog=num –is assigned parameter backlog in call listen(2). By缺省值backlog it is equal to -1. rcvbuf=size –is assigned parameter SO_RCVBUF for listening socket. sndbuf=size –is assigned parameter SO_SNDBUF for listening socket. accept_filter=filter –is assigned name accept-filter. It works only to FreeBSD, it is possible to use two filters –dataready and httpready. On the signal -HUP accept-filter it is possible to change only in the quite last versions FreeBSD: 6.0, 5.4-STABLE and 4.11-STABLE. deferred –indicates to use that postponed accept(2) on Linux with the aid of option TCP_DEFER_ACCEPT. bind –indicates that it is necessary to make bind(2) separately for this pair of address:port. The fact is that if are described several directives listen with the identical port, but by different addresses and one of the directives listen listens to on all addresses for this port (*:port), then nginx will make bind(2) only to *:port. It is necessary to consider that in

2.2.配置说明Chapter2.基本配置

this case for determining the address, on which the connections ar-rive, is done the system call getsockname(). But if are used parameters backlog, rcvbuf, sndbuf, accept_filter or deferred, then it is always done separately for this pair of address:port bind(2). Example of the use of the parameters:listen 127.0.0.1缺省值accept_filter=dataready backlog=1024;

location

语法: location [=|~|~*|^~] /uri/ { … }

缺省值: no context: server This directive allows different con-figurations depending on the URI. It can be configured using both conventional strings and regular expressions. To use regular expres-sions, you must use the prefix ~* for case insensitive match and ~ for case sensitive match. To determine which location directive matches a particular query, the conventional strings are checked first. Con-ventional strings match the beginning portion of the query and are case-sensitive -the most specific match will be used (see below on how nginx determines this). Afterwards, regular expressions are checked in the order defined in the configuration file. The first regular expres-sion to match the query will stop the search. If no regular expression matches are found, the result from the convention string search is used. There are two ways to modify this behavior. The first is to use the prefix ―=‖, which matches an exact query only. If the query matches, then searching stops and the request is handl ed immediately. For example, if the request ―/‖ occurs frequently, then using ―location = /‖ will expedite the processing of this request. The second is to use the prefix ^~. This prefix is used with a conventional string and

tells nginx to not check regul ar expressions if the path provided is a match. For instance, ―location ^~ /images/‖ would halt searching if the query begins with /images/ -all regular expression directives would not be checked. Furthermore it is important to know that NGINX does the comparison not URL encoded, so if you have a URL like ―/ images/%20/test‖ then use ―/images/ /test‖ to determine the location. To summarize, the order in which directives are checked is as follows: Directives with the = prefix that match the query exactly. If found, searching stops. All remaining directives with conventional strings, longest match first. If this match used the ^~ prefix, searching stops. Regular expressions, in order of definition in the configuration file. If #3 yielded a match, that result is used. Else the match from #2 is used. Example:

1 location = / {

2 # matches the query / only.

3 [ configuration A ]

4}

5 location / {

6 # matches any query , since all queries begin with /, but regular

7 # expressions and any longer conventional blocks will be

Chapter2. 基本配置2.2. 配置说明

8 # matched first .

9 [ configuration B ]

10 }

11 location ^~ / images / {

12 # matches any query beginning with / images / and halts

searching ,

13 # so regular expressions will not be checked .

14 [ configuration C ]

15 }

16 location ~* \.( gif | jpg | jpeg )$ {

17 # matches any request ending in gif , jpg , or jpeg .

However , all

18 # requests to the / images / directory will be handled

by

19 # Configuration C.

20 [ configuration D ]

21 }

Example requests: / -> configuration A /documents/document.html -> configuration B /images/1.gif -> configuration C /documents/1.jpg -> configuration D Note that you could define these 4 configurations in any order and the results would remain the same. How nginx Determines Which Path Matches Most users will not need to know how nginx internally determines which path to use -know that it will choose the ―most specific‖ match for your URL in a speedy and efficient manner. For those that are curious, however, read on. All path strings are sorted alphabetically. nginx then proceeds to search down the list looking for matches until the request URI has a ―higher‖ value then the current string in the sorted list. This is determined using the family of strcmp() functions -once strcmp() returns 1, then searching stops. Once searching stops, the last string which matched is used. For example, lets say we have the following paths: / /a /apple /banana Now, lets say the server gets the path ―/az‖. nginx would begin search down this list. First, ―/‖ would match, but ―/ is less than ―/az‖ so searching continues. ―/a‖ also matches, but ―/a‖ is still less than ―/ az‖ so we continue again. ―/apple‖ does not match. The

next string, ―/ banana‖, is greater than ―/az‖ so searching stops and the last match, ―/a‖, would be used.

msie_padding

语法: msie_padding [on|off]

缺省值: msie_padding on context: http, server, location This directive enables or disables the the msie_padding feature for MSIE browsers. When this is enabled Nginx will pad the size of the response headers up to 512 bytes for responses with status codes of more than 400. This prevents activating the ―friendly‖ http error pages feature of the relevant browsers, so as to not hide the possibly more informative error pages.

msie_refresh

2.2.配置说明Chapter2.基本配置

语法: msie_refresh [on|off]

缺省值: msie_refresh off context: http, server, location This directive allows or forbids issuing a refresh instead of doing a redirect for MSIE.

optimize_server_names

语法: optimize_server_names [ on|off ]

缺省值: optimize_server_names on context: http, server Directive activates or deactivates optimization of host name checks for name-based virtual servers. In particular, the check influences the name of the host used in redirects. If optimization is on, and all name-based servers listening on one address:port pair have identical configura-tion, then names are not checked during request execution and redirects use first server name. If redirect must use host name passed by the client, then the optimization must be turned off.

port_in_redirect

语法: port_in_redirect [ on|off ]

缺省值: port_in_redirect on context: http, server, location Di-rective allows or prevents port indication in redirects handled by nginx.

recursive_error_pages

语法: recursive_error_pages [on|off]

缺省值: recursive_error_pages off context: http, server, loca-tion recursive_error_pages enables or disables following a chain of error_page directives.

root

语法: root path

缺省值: root html context: http, server, location, if in location root specifies the document root for the requests. For example, with this configuration

1 location /i/ {

2 root /spool/w3; 3}

A request for ―/i/top.gif‖ will return the file ―/spool/w3/i/ top.gif‖. You can use variables in the argument.

satisfy_any

语法: satisfy_any [ on|off ]

缺省值: satisfy_any off context: location Directive solves access with at least one successful checking, executed by modules ngx_http_access_module or ngx_http_auth_basic_module:

1 location / {

2 satisfy_any on;

3 allow 192.168.1.0/32;

Chapter2.基本配置2.2.配置说明

4 deny all ;

5 auth_basic ‖ closed site ―;

6 auth_basic_user_file conf / htpasswd ;

7 }

send_timeout

语法: send_timeout the time

缺省值: send_timeout 60 context: http, server, location Directive assigns response timeout to client. Timeout is established not on entire transfer of answer, but only between two operations of reading, if after this time client will take nothing, then nginx is shutting down the connection.

sendfile

语法: sendfile [ on|off ]

缺省值: sendfile off context: http, server, location Directive activate or deactivate the usage of sendfile().

server

语法: server {…}

缺省值: no context: http Directive assigns configuration for the virtual server. There is no clear separation of the virtual servers ip-based (on the basis ip-address) and name-based (on the basis of the name, transferred in the line ―Host‖ of the title of request). Instead of this by directives listen are described all addresses and ports, on which it is necessary to assume connections for this server, and in directive server_name are indicated all names of servers. The example to configurations is described in tuning of virtual servers.

server_name

语法: server_name name [... ]

缺省值: server_name hostname context: server Directive assigns the names of virtual server, for example: server { server_name https://www.wendangku.net/doc/b54999586.html, https://www.wendangku.net/doc/b54999586.html,; } The first name becomes the basic name of server. By缺省值the name of the machine (hostname) is used. It is possible to use ―*‖ for replacing the first part of the name: server { server_name https://www.wendangku.net/doc/b54999586.html, *https://www.wendangku.net/doc/b54999586.html,; } Two of the given name of the above example can be combined into one: server { server_name https://www.wendangku.net/doc/b54999586.html,; } The basic name of server is used in an HTTP redirects, if no a ―Host‖ header was in client request or that header does not match any assigned server_name. You can also use just ―*‖ to force Nginx to use the ―Host‖ header in the HTTP redirect (note that ―*‖ cannot be used as the first name, but you can use a dummy name such as ―_‖ instead): server { server_name https://www.wendangku.net/doc/b54999586.html, *; } server { server_name _ *; }

server_names_hash_max_size

语法: server_names_hash_max_size number

缺省值: server_names_hash_max_size 512 context: http Directive

2.2.配置说明Chapter2.基本配置

assigns the maximum size of the hash-tables of the names of servers. In greater detail see in the description of tuning hash.

server_names_hash_bucket_size

语法: server_names_hash_bucket_size number

缺省值: server_names_hash_bucket_size 32/64/128 context: http Directive assigns the size of basket in the hash-tables of the names of servers.This value by缺省值depends on the size of the line of processor cache. In greater detail see in the description of tuning hash.

tcp_nodelay

语法: tcp_nodelay [on|off]

缺省值: tcp_nodelay on context: http, server, location This di-rective allows or forbids the use of the socket option TCP_NODELAY. Only included in keep-alive connections. Want to know more about the TCP_NODELAY socket option? ReadMoreAboutTcpNodelay

tcp_nopush

语法: tcp_nopush [on|off]

缺省值: tcp_nopush off context: http, server, location This di-rective permits or forbids the use of the socket options TCP_NOPUSH on FreeBSD or TCP_CORK on Linux. This option is only available when using sendfile. Setting this option causes nginx to attempt to send it‘s HTTP response headers in one packet on Linux and FreeBSD 4.x ReadMoreAboutTcpNopush

types

语法: typ es {…} context: http, server, location Directive as-signs the correspondence of expansion and MIME-types of answers. Toone MIME-type can correspond several expansions. By缺省值it is used these correspondences:

1 types {

2 text / html html ;

3 image / gif gif ;

4 image / jpeg jpg ;

5 }

The sufficiently complete table of mappings is included and is located in file conf/mime.types. So that for that determined location‘a for all answers would reveal MIME-type ―application/octet-stream‖, it is possible to use the following:

1 location /download/ {

2 types { }

3 default_type application/octet.stream;

4}

Chapter2.基本配置2.2.配置说明

http配置

The module ngx_http_core_module supports the built-in variables, whose names correspond with the names of variables in Apache. First of all, these are the variables, which represent the lines of the title of the client request, for example,

$http_user_agent, $http_cookie and so forth. Furthermore, there are other variables:

$args, this variable is equal to arguments in the line of request;

$content_length, this variable is equal to line ―Content-Length‖ in the header of request; $content_type, this variable is equal to line ―Content-Type‖ in the header of request; $document_root, this variable is equal to the value of directive root for the current request;

$document_uri, the same as $uri;

$host, this variable is equal to line ―Host‖ in the header of request or name of the server, to whom the request arrived, if there is no this line;

$limit_rate, the variable allows to limit connection rate;

$request_method, this variable is equal to the method of request, usually this ―GET‖ or ―POST‖; $remote_addr, this variable is equal to the address of client; $remote_port, this variable is equal to the port of client;

$remote_user, this variable is equal to the name of user, authen-ticated by ngx_http_auth_basic_module; $request_filename, this variable is equal to path to the file for the current request, formed from directives root or alias and URI request; $request_body_file, ??? $request_uri, this variable is equal to the complete initial URI together with the arguments;

$query_string, the same as $args;

$scheme, the HTTP scheme (http, https). Evaluated only on demand, for example: rewrite ^(.+)$ $scheme://https://www.wendangku.net/doc/b54999586.html,$1 redirect;

$server_protocol, this variable is equal to the protocol of re-quest, usually this ―HTTP/1.0″ or ―HTTP/1.1″;

$server_addr, the variable is equal to the server address, to whom arrived the request. As a rule, for obtaining the value of this variable is done one system call. In order to avoid system call, it is necessary to indicate addresses in directives listen and to use parameter bind;

$server_name, this variable is equal to the name of the server, to whom arrived the request;

$server_port, this variable is equal to the port of the server, to which the request arrived;

$uri, this variable is equal to current URI in the request, it can differ from initial, for example by internal redirects, or with the

2.2.配置说明Chapter2.基本配置

use of index it is file with internal redirects.

常用配置举例nginx目录自动加斜线

1 if (.d $request_filename ){

2 rewrite ^/(.*) ([^/]) $ http :// $host / $1$2 / permanent ;

3 }

nginx防盗链

1.

针对不同的文件类型

2.

针对不同的目录

1 # Preventing hot linking of images and other file types

2 location ~* ^.+\.( gif | jpg | png | swf | flv | rar | zip )$ {

3 valid_referers none blocked server_names *. linuxtone .

org http :// localhost baidu . com ;

4 if ( $invalid_referer ) {

5 rewrite ^/ http :// www . linuxtone . org / images /

default / logo . gif ;

6 # return 403;

7 }

8 }

1 location / img / {

2 root / data / www / wwwroot / bbs / img /;

3 valid_referers none blocked server_names *. linuxtone .

org http :// localhost baidu . com ;

4 if ( $invalid_referer ) {

5 rewrite ^/ http :// www . linuxtone . org / images /

default / logo . gif ;

6 # return 403;

7 }

8 }

nginx expires

1.根据文件类型expires

1 # Add expires header for static content

2 location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ {

3 if (.f $request_filename) {

4 root /data/www/wwwroot/bbs;

5

expires 1d;

Chapter2. 基本配置2.3. 启动和控制

6 7 8 } } break ;

2.根据判断某个目录

1 # serve static files

2 location ~ ^/( images | javascript | js| css | flash | media | static

)/ {

3 root / data / www / wwwroot / down ;

4 expires 30 d;

5 }

nginx下载限制并发和速率

1

2 limit_zone one $binary_remote_addr 10 m;

3 server {

4 listen 80;

5 server_name down . linuxotne . org ; index index . html

index . htm index . php ;

6 root / data / www / wwwroot / down ;

7 # Zone limit

8 location / {

9 limit_conn one 1;

10 limit_rate 20 k;

11 }

2.3启动和控制

nginx是超级稳定的服务器,一般不会因为超载问题而需要重启,重启的目的一般都是修改配置文件后需要加载一下。最开始的时候,我是用最直接的重启方式killall -9 nginx;/data/nginx/sbin/nginx如果机器比较慢,kill进程时一瞬间杀不完,再执行一次即可。这种重启方式不是特别安全,如果配置有误,则会重启失败,需要重新修改配置文件然后再启动,期间会消耗一点时间。不过对于目前普遍还是不怎么严格的http界而言,这点时间还不至于产生太大损失,只要不是在关键时刻搞出来就好。如果希望沿用这种重启办法,我提议还是先好好测试吧。后来我在https://www.wendangku.net/doc/b54999586.html,上看到了一种更奇妙的重启kill-HUP$pid($pid就是nginxmaster进程的进程号)我一般这样用

kill .HUP `cat / data / nginx / logs / nginx .pid `

这种方式的好处是实现―平滑重启‖,在ps-aux中可以看到,nginx首先启动新进程,旧的进程仍然提供服务,在一段时间后,旧的进程服务结束就自动关闭,剩下新进程继续服务。但是这种方式也是有缺点的,如果配置文件有误,或者资源冲突,则重启失效,但nginx并没有任何的提示!这就会时常发现改动的配置文件没有生效,又比较难找到问题。所以,最后杂和了一下问题,

2.3.启动和控制Chapter2.基本配置

弄了一个nginx.sh,这个版本的nginx.sh还是没有解决kill-HUP的资源冲突的问题,但解决了配置文件的问题。资源冲突的比如80端口被占用、日志文件目录没有创建这种的,我再想想办法。

1

#!/ bin/sh

2 BASE_DIR =‘/data/‘

3 ${BASE_DIR}nginx/sbin/nginx .t .c ${BASE_DIR}nginx/conf/

nginx.conf > & ${BASE_DIR}nginx/logs/nginx.start 4 info =` cat ${BASE_DIR}nginx/logs/nginx.start ` 5 if [`echo $info | grep .c "syntax is ok " ` .eq 1 ]; then 6 if [`ps aux|grep "nginx "|grep .c "master" ` == 1 ];

then 7 kill .HUP `cat ${ BASE_DIR } nginx / logs / nginx .pid ` 8 echo ―ok ‖

9

else

10

killall .9 nginx

11

sleep 1 12 ${BASE_DIR}nginx/sbin/nginx

13

fi

14

else 15 echo ―######## error: ########‖ 16 cat ${BASE_DIR}nginx/logs/nginx.start

17

fi

Chapter 3

深入源码

3.

1源码结构

3.

2configure配置

3.

3nginx源码习惯

为了能更好的看懂代码,需要对nginx的源码习惯有所了解,这样读源码会更加容易一些,在所有的nginx的中实现的模块都有一个ngx_前缀,包括源文件的文件名,结构体和函数。http模块中的结构体和函数以ngx_http作为前缀。

nginx的数组的使用习惯,如下面/src/http/ngx_http_upstream.c文件中的代码所示:

1 if (uscf.>servers == NULL ) {

2 uscf.>servers = ngx_array_create (cf.>pool , 4, sizeof (

ngx_http_upstream_server_t ));

3 if (uscf .>servers == NULL ) {

4 return NGX_CONF_ERROR ;

5 }

6 }

7

8 us = ngx_array_push (uscf.>servers );

9 if (us == NULL ) {

10 return NGX_CONF_ERROR ;

11 }

12

13 ngx_memzero (us , sizeof ( ngx_http_upstream_server_t ));

如上面的代码所示,数组首先调用ngx_array_create创建一个数组对象,然后调用ngx_array_push函数得到一个指针,这个指针指向一个对象,该对象的内存已经分配好了,可以直接使用。首先使用一个指针指向数组结构的elts字段,这样就得到了一个数组,该数组的大小为数组结构体的nelts字段,使用的方式如下所示:

3.4.常用基础库Chapter3.深入源码

1 uscfp = umcf.>upstreams.elts;

2 for (i = 0; i < umcf.>upstreams.nelts; i++) {

3 if ( uscfp [i].>host.len != u.>host.len ||

ngx_strncasecmp ( uscfp [i].>host.data, u.>host .data , u.>host.len)!= 0){

4

continue ; 5} 6}

对于其他数据结构的使用大致如此,在后面的讲解基础结构的时候详细解释。

在内存使用方面,尽量使用nginx提供的内存使用方式,在初始化或是需要长时间保存的内存尽量采用在cf->pool(即由全局配置分配的内存池)中分配内存的方式来分配内存,在每个请求

3.4常用基础库

由于c语言没有C++或是java那样丰富的库函数,所以一般会自己实现一些相对简单却非常实用的库函数,在nginx中有很多值得学习的基础库函数。在本书中只介绍一些使用频繁或是设计精巧的库函数。如果您是一个经验丰富的linux开发人员,本章可以略过。

字符串

任何一门编程语言中,字符串的操作都是最基本的知识,所以把这个基本操作单列出来。该模块在ngx_string.h和ngx_string.c中。字符串的操作一般包括:初始化,复制,格式化输出,大小写转换,查找子字符,查找子字符串,字符串转换成数字,字符串编码类型相关函数,字符串比较,trim,split等函数。在这个类中间没有调用其他模块的函数,作为一个http服务器,还需要实现URL转换,简单的html转换等函数。字符串的结构体非常简单实用,是非常值得刚入门的linux开发工程师学习的。字符串的结构体为ngx_str_t,其两个字段如下:

Table 3.1:字符串结构体字段

字段说明

len 字符串长度

data 字符串指针

字符串结构体由两个字段构成,一个是字符串的长度,一个字符串的首指针。这种结构体可以使得在使用字符串的时候异常简单,但是nginx的实现不够彻底还是有些使用c的字符串规则的函数,即以0作为字符串的最后一个字符。字符串函数如下表所列:

Chapter3.深入源码3.4.常用基础库

Table 3.2:字符串结构体字段

函数说明

ngx_string 初始化函数

ngx_null_string 初始化空字符串函数

ngx_tolower 字符转小写函数

ngx_toupper 字符转大写函数

ngx_strncmp 比较指定长度的字符串是否相同

ngx_strcmp 比较字符串是否相同

ngx_strstr 从字符串中找到需要的字符串

ngx_strlen 字符串的长度

ngx_strchr 在字符串中找到匹配的字符,返回0为匹

ngx_strlchr 在字符串中找到匹配的字符,返回匹配的

指针

ngx_memzero 把一片内存区设置为0

ngx_memset 把一片内存区设置为指定的数

ngx_memcpy 复制内存,没有返回

ngx_cpymem 复制内存,返回复制完了dst的最后一个

字符的下一个字符的指针

ngx_copy 同ngx_cpymem

ngx_memcmp 比较内存中的数据是否相同

ngx_strlow 把字符串都转换成小写

ngx_cpystrn 复制字符串,并且返回字符串的最后一个

字符的下一个字符的指针

ngx_pstrdup 复制字符串到pool,返回字符串的指针

ngx_sprintf 把各种类型的数据格式化输出到buf,最

大的长度为65536

ngx_snprintf 把各种类型的数据格式化输出到指定长度

的buf

ngx_strcasecmp 不分大小写比较两个字符串是否相同

ngx_strncasecmp 指定长短不分大小写比较两个字符串是否相同

ngx_strnstr 在指定大小一个字符串中是否有子字符串

ngx_strstrn 在一个字符串中是否有子指定大小的字符

ngx_strcasestrn 在一个字符串中是否有子指定大小的字符串,不区分大小写

ngx_rstrncmp 从后往前比较两个字符串是否相同,返回

相同的位置

ngx_rstrncasecmp 从后往前比较两个字符串是否相同,返回相同的位置,不区分大小写

ngx_memn2cmp 比较两个指定长度的内存是否相同,也比较长的内存是否包含短的内存

ngx_atoi 指定长度的字符串转换成数字

ngx_atosz 指定长度的字符串转换成ssize_t类型数

ngx_atoof 指定长度的字符串转换成off_t类型数字

ngx_atotm 指定长度的字符串转换成time_t类型数字

3.4.常用基础库Chapter3.深入源码

续表3.8

函数说明

ngx_hextoi 指定长度的字符串转换成十六进制数字

ngx_hex_dump 把数字转换成16进制的字符串

ngx_encode_base64 base64编码

ngx_decode_base64 base64解码

ngx_utf8_decode 把utf8字符解码成双字节的unicode或是

单字节字符,但是该函数会移动*p的值,

请注意

ngx_utf8_length 得到utf8编码的字符占几个字节

ngx_utf8_cpystrn 赋值utf8字符串,保证完整的复制

ngx_escape_uri 对uri进行编码

ngx_unescape_uri 对uri的进行解码

ngx_escape_html 对html进行编码

ngx_sort 排序,主要是用于数组排序

ngx_qsort 快速排序

ngx_value 把宏数字转换成字符串

为了测试,我们可以用以下两种方式打印出来

1 ngx_str_t str ;

2 printf (‖ %* s‖ , str . len , str . data );

3 peinrf (‖%V‖, & str );

内存分配

Nginx的内存分配的技巧很值得我们学习,设计的是非常精巧的,它会根据不同的生存周期建立起一系列的内存pool,在需要使用内存的时候,直接在pool中获取内存即可。这种方法既加快了速度,又能够非常方便的管理内存,避免内存泄露。涉及到内存分配的文件主要有ngx_alloc.h,ngx_alloc.c,ngx_buf.c,ngx_output_chain.c,ngx_buf.h,ngx_palloc.h 和ngx_palloc.c。

我们在讲解对内存池的创建和使用之前,我们先讲解一下封装的基本的分配内存的函数:

ngx_alloc

这个函数实际上是调用malloc()函数,但是记录了日志。C语言跟内存申请相关的函数主要有alloc,calloc,malloc,free,realloc,sbrk等,其中alloc是向栈申请内存,因此无需释放,malloc分配的内存是位于堆中的,并且没有初始化内存的内容,因此基本上malloc之后,调用函数memset来初始化这部分的内存空间,calloc则将初始化这部分的内存,设置为0,而realloc则对malloc申请的内存进行大小的。ngx_calloc

这个函数调用了ngx_alloc分配了内存之后,调用ngx_memzero把分配的内存都置为0。

ngx_memalign

Chapter3.深入源码3.4.常用基础库

这个函数在linux下实际封装调用了memalign函数。能够分配连续的内存块。这个函数主要在分配大块的内存的时候使用。

ngx_free

这个函数就是free函数的宏定义。

内存池的结构体如下代码所示

1 struct ngx_pool_s {

2 ngx_pool_data_t d;

3 size_t max ;

4 ngx_pool_t * current ;

5 ngx_chain_t * chain ;

6 ngx_pool_large_t * large ;

7 ngx_pool_cleanup_t * cleanup ;

8 ngx_log_t * log ;

9 };

2019年nginx安装手册

Nginx安装手册 1nginx安装环境 nginx是C语言开发,建议在linux上运行,本教程使用作为安装环境。 ?gcc 安装nginx需要先将官网下载的源码进行编译,编译依赖gcc环境,如果没有gcc环境,需要安装gcc:yum install gcc-c++ ?PCRE PCRE(Perl Compatible Regular Expressions)是一个Perl库,包括perl 兼容的正则表达式库。nginx的http模块使用pcre来解析正则表达式,所以需要在linux上安装pcre库。yum install -y pcre pcre-devel 注:pcre-devel是使用pcre开发的一个二次开发库。nginx也需要此库。 ?zlib zlib库提供了很多种压缩和解压缩的方式,nginx使用zlib对http包的内容进行gzip,所以需要在linux上安装zlib库。 yum install -y zlib zlib-devel ?openssl OpenSSL 是一个强大的安全套接字层密码库,囊括主要的密码算法、常用的密钥和证书封装管理功能及SSL协议,并提供丰富的应用程序供测试或其它目的使用。 nginx不仅支持http协议,还支持https(即在ssl协议上传输http),所以需要在linux 安装openssl库。 yum install -y openssl openssl-devel 2编译安装 将拷贝至linux服务器。 解压: tar -zxvf --help查询详细参数(参考本教程附录部分:nginx编译参数) 参数设置如下: ./configure \ --prefix=/usr/local/nginx \ --pid-path=/var/run/nginx/ \ --lock-path=/var/lock/ \ --error-log-path=/var/log/nginx/ \

在centos上搭建nginx图片服务器(包含上传模块)

安装Nginx 和相关的插件 (Image Filter Module & Upload Module & Upload Progress Module) (1) install essential sys library $ yum -y install gcc-c++ $ yum -y install zlib zlib-devel openssl openssl-devel pcre pcre-devel gd gd-devel (2)install nginx & related module plugin $ wget https://https://www.wendangku.net/doc/b54999586.html,/masterzen/nginx-upload-progress-module/archive/v0.9.1.tar.gz $ wget https://https://www.wendangku.net/doc/b54999586.html,/vkholodkov/nginx-upload-module/archive/2.2.0.tar.gz $ wget https://www.wendangku.net/doc/b54999586.html,/download/nginx-1.3.8.tar.gz $ tar zxvf *.tar.gz $ cd /nginx-1.3.8/conf (3)configure nginx.conf $ vi nginx.conf #user root; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for"';

手把手教你开发Nginx模块

手把手教你开发Nginx模块 前面的哪些话 关于Nginx模块开发的博客资料,网上很多,很多。但是,每篇博客都只提要点,无法"step by step"照着做,对于初次接触Nginx开发的同学,只能像只盲目的蚂蚁瞎燥急!该篇文章没有太多技术深度,只是一步一步说明白Nginx模块的开发过程。 开发环境搭建 工欲善其事,必先利其器。个人推荐Eclipse CDT 作为IDE,原因很简单,代码提示与补全功能很全,完胜Codeblock这类...相信与否,试过就知道。 在ubuntu下搭建开发环境: 安装GCC编译器 apt-get install build-essential 安装pcre/openssl/zlib开发库 apt-get install libpcre3-dev apt-get install libssl-dev apt-get install libzip-dev 必需安装nginx核心模块依赖的pcre,openssl,zilib开发库 安装JRE/Eclipse CDT apt-get install openjdk-8-jre wget http://ftp.yz.yamagata-u.ac.jp/pub/eclipse//technology/epp/downloads/release/neon/R/eclipse-cpp-neon-R-linux-gtk-x86_64.tar.gz && tzr -xzvf eclipse-cpp-neon-R-linux-gtk-x86_64.tar.gz 下载nginx源码 wget https://www.wendangku.net/doc/b54999586.html,/download/nginx-1.10.1.tar.gz && tar -xzvf nginx-1.10.1.tar.gz 配置CDT Build Environment 添加变量,值Nginx src下各模块路径,用冒号分隔,例如: /root/Workspace/nginx-1.10.1/src/core:/root/Workspace/nginx-1.10.1/src/event:/root/Workspace/nginx-1.10.1/src/http:/root/Workspace/nginx-1.10.1/src/mail:/root/Workspace/n ginx-1.10.1/src/stream:/root/Workspace/nginx-1.10.1/src/os/unix 添加环境变量,创建C项目时自动作为-I选项 image image Nginx模块编译流程 Nginx使用configure脚本分析环境,自动生成objs结果。哪么configure如何编译第三方模块?答案是--add-module指定第三方模块目录,并将目录存为$ngx_addon_dir环境变量。执行$ngx_addon_dir/config脚本,读取模块配置。在config中的环境变量分为2种:小写的本地环境变量,大写的全局环境变量。例如: ngx_addon_name=ngx_http_mytest_module

Eclipse + nginx module + debug

Liunx下使用Eclipse 开发nginx module,进行单步调试 Author: chuantong.huang@https://www.wendangku.net/doc/b54999586.html, Date:2010-10-26 1)取Nginx最新代码: wget https://www.wendangku.net/doc/b54999586.html,/download/nginx-0.7.67.tar.gz tar -xvf nginx-0.7.67.tar.gz cd nginx-0.7.67 2)建立模块目录与代码 pwd # 进入Nginx源代码目录,如: /home/toon/workspace/nginx-0.7.67 mkdir ngx_module_echo vim ngx_module_echo/config 其内容为: ngx_addon_name=ngx_module_echo HTTP_MODULES="$HTTP_MODULES ngx_module_echo" NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/ngx_module_echo.c" CORE_LIBS="$CORE_LIBS " vim ngx_module_echo/ngx_module_echo.c 其内容: 参考nginx的echo模块代码,自己google下,或参考以下: https://www.wendangku.net/doc/b54999586.html,/p/ngx_ext.html 3)建立Makefile 利用nginx提供的configrue脚本生成Makefile文件: ./configure --without-http_rewrite_module --without-http-cache --add-module=/home/toon/workspace/nginx-0.7.67/ngx_module_echo/ --with-debug 注意:这里要指定moduel目录(与Nginx源码目录下),还要指定debug编译. BTW:Eclipse 中执行Build project时会执行make clean all,会删除Makefile,故此时应该再执行configure生成Makefile 可以先make一次,编译出objs/nginx文件。

Windows下编译Nginx并添加模块

Windows下编译Nginx并添加模块 一.准备工作 1.环境安装 1.安装vs2010或vs2013等vs工具。 2.安装ActivePerl,安装完成后,将其安装路径加入到PATH环境变量。 3.安装MinGW,下载mingw-get-setup.exe,安装完成后,将其安装路径加入到PATH环境变量。(记得安装的时候装上msys,不懂就全勾了) 4.安装nasm,安装完成后,将其安装路径加入到PATH环境变量。 2.下载编译nginx源码文件 1.nginx源码:nginx-1.1 2.2 2.pcre:pcre-8.40 3.zlib:zlib-1.2.11 4.openssl:openssl-1.0.2l 3.下载添加模块文件 1.文件上传模块: nginx-upload-module 2.rtmp模块:nginx-rtmp-module 3.文件上传进度条模块:nginx-upload-progress-module 二.编译并添加模块 1.将上述7个压缩包文件解压至文件夹msys文件目录下,如C:\MinGW\msys\1.0\home\$UESRNAME\。 2.找到msys.bat的路径并双击msys.bat,运行。如下图所示

3.打开msys.bat后如下所示 右击上方编辑栏,选择编辑,粘贴,可进行粘贴复制功能。 4.cd 至nginx源码路径,并在源码路径下执行下面语句: auto/configure --with-cc=cl --builddir=objs --prefix= \ --conf-path=conf/nginx.conf --pid-path=logs/nginx.pid \ --http-log-path=logs/access.log --error-log-path=logs/error.log \ --sbin-path=nginx.exe --http-client-body-temp-path=temp/client_body_temp \ --http-proxy-temp-path=temp/proxy_temp \ --http-fastcgi-temp-path=temp/fastcgi_temp \ --with-cc-opt=-DFD_SETSIZE=1024 --with-pcre=../pcre-8.40 \ --with-zlib=../zlib-1.2.11 --with-openssl=../openssl-1.0.2l \ --with-select_module --with-http_ssl_module \ --with-http_sub_module \ --add-module=../nginx-upload-module-2.255 \ --add-module=../nginx-upload-progress-module-master \ --add-module=../nginx-rtmp-module-master \ 其中pcre,zlib,openssl的语句需根据版本号的不同进行改变,最后增加的模块也需更具实际情况进行相应的改变,步骤4操作如下图所示:

系统概要设计报告(模板)

xx平台 系统概要设计 版本<1.0>

文档信息及版本历史 版权信息 本文件内容由【xx公司】负责解释 本文件的版权属于【xx公司】 任何形式的散发都必须先得到本文档版本所属单位的许可

【目录】 1概述 (4) 1.1编写目的 (4) 1.2适用范围 (4) 1.3读者对象 (4) 1.4术语和缩写 (4) 1.5参考资料 (4) 2设计概述 (5) 2.1设计约束 (5) 2.2设计策略 (5) 2.3技术实现 (5) 3系统概述 (5) 4系统总体结构 (6) 4.1物理结构 (6) 4.2逻辑结构 (6) 5短息服务器 (7) 5.1短信发送流程............................................................................. 错误!未定义书签。 5.2短信接收流程............................................................................. 错误!未定义书签。 5.3订阅流程(短信方式) (7) 5.4取消订阅流程(短信方式)..................................................... 错误!未定义书签。6医疗短信平台WEB系统.. (8) 6.1医院注册流程............................................................................. 错误!未定义书签。 6.2后台管理流程............................................................................. 错误!未定义书签。 6.3订阅/取消订阅流程(WEB方式) (9) 7运行环境 (9) 7.1软件平台 (9) 7.2硬件平台 (9) 8系统备份设计 (10) 9系统容错设计 (10) 10设计约定 (10) 11待解决问题 (10)

Nginx的介绍和使用

1.什么是Nginx Nginx(发音同engine x)是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like 协议下发行。由俄罗斯的程序设计师Igor Sysoev所开发,最初供俄国大型的入口网站及搜寻引擎Rambler(俄文:Рамблер)使用。其特点是占有内存少,并发能力强,事实上nginx的并发能力确实在同类型的网页伺服器中表现较好.目前中国大陆使用nginx网站用户有:新浪、网易、腾讯,另外知名的微网志Plurk 也使用nginx。 优点: (1)Nginx 可以在大多数 Unix like OS 上编译运行,并有 Windows 移植版。 Nginx 的1.2.6稳定版已经于2012年12月11日发布,[1]1.3.10开发版已经于2012年12月25日发布,如果新建站点,建议使用最新稳定版作为生产版本,已有站点升级急迫性不高。Nginx 的源代码使用 2-clause BSD-like license。 (2)Nginx 是一个很强大的高性能Web和反向代理服务器,它具有很多非常优越的特性: 在高连接并发的情况下,Nginx是Apache服务器不错的替代品:Nginx在美国是做虚拟主机生意的老板们经常选择的软件平台之一。能够支持高达 50,000 个并发连接数的响应,感谢Nginx为我们选择了 epoll and kqueue作为开发模型。 (3)Nginx作为负载均衡服务器:Nginx 既可以在内部直接支持 Rails 和 PHP 程序对外进行服务,也可以支持作为 HTTP代理服务器对外进行服务。Nginx采用C进行编写,不论是系统资源开销还是CPU使用效率都比 Perlbal 要好很多。 作为邮件代理服务器:Nginx 同时也是一个非常优秀的邮件代理服务器(最早开发这个产品的目的之一也是作为邮件代理服务器),Last. fm 描述了成功并且美妙的使用经验。 (4)Nginx 是一个安装非常的简单,配置文件非常简洁(还能够支持perl语法),Bugs非常少的服务器:Nginx 启动特别容易,并且几乎可以做到7*24不间断运行,即使运行数个月也不需要重新启动。你还能够不间断服务的情况下进行软件版本的升级。 2.下载和安装Nginx Nginx的官方网站是https://www.wendangku.net/doc/b54999586.html,/cn/,英文主页为https://www.wendangku.net/doc/b54999586.html,,从这里可以获得Nginx 的最新版本信息。Nginx有三个版本:稳定版、开发版和历史稳定版。开发版更新较快,包含最新的功能和bug的修复,但同时也可能会遇到新的bug,开发版一旦更新稳定下来,就会被加入稳定版分支中。然而有些新功能不一定会被加到旧的稳定版中去。稳定版本更新较慢,但是bug较少,可以作为生产环境的首选,因此通常建议使用稳定版。历史稳定版本为以往稳定版本的汇总,不包含最新的功能。 这里选择当前的稳定版本nginx-0.7.65作为介绍对象,开始介绍编译安装。在安装Nginx 之前,确保系统已经安装了gcc、 openssl-devel、 pcre-devel和zlib-devel软件库。Linux开发库是在安装系统时通过手动选择安装的,gcc、 openssl-devel、zlib-devel三个

NGINX 介绍

优点 Nginx性能概述 常见问题(FAQ) 安装Nginx 优点 Nginx性能概述 常见问题(FAQ) 安装Nginx 展开 nginx map Nginx 可以在大多数Unix like OS 上编译运行,并有Windows 移植版。目前Nginx 的1.0.0稳定版已发布,开发版本为0.9.x,稳定版为0.8.x,历史稳定版为 0.7.x,建议使用0.8系列作为生产版本。 Nginx 的源代码使用2-clause BSD-like license。 Nginx 是一个很牛的高性能Web和反向代理服务器,它具有很多非常优越的特性: 在高连接并发的情况下,Nginx是Apache服务器不错的替代品:Nginx 在美国是做虚拟主机生意的老板们经常选择的软件平台之一。能够支持高

达50,000 个并发连接数的响应,感谢Nginx为我们选择了epoll and kqueue作为开发模型。 Nginx作为负载均衡服务器:Nginx 既可以在内部直接支持Rails 和PHP 程序对外进行服务,也可以支持作为 HTTP代理服务器对外进行服务。Nginx采用C进行编写,不论是系统资源开销还是CPU使用效率都比Perlbal 要好很多。 作为邮件代理服务器:Nginx 同时也是一个非常优秀的邮件代理服务器(最早开发这个产品的目的之一也是作为邮件代理服务器),Last. fm 描述了成功并且美妙的使用经验。 Nginx 是一个安装非常的简单,配置文件非常简洁(还能够支持perl 语法),Bugs非常少的服务器:Nginx 启动特别容易,并且几乎可以做到7*24不间断运行,即使运行数个月也不需要重新启动。你还能够不间断服务的情况下进行软件版本的升级。 编辑本段Nginx性能概述 HTTP基础功能 处理静态文件,索引文件以及自动索引; 反向代理加速(无缓存),简单的负载均衡和容错; FastCGI,简单的负载均衡和容错; 模块化的结构。过滤器包括gzipping, byte ranges, chunked responses, 以及 SSI-filter 。在SSI过滤器中,到同一个proxy 或者FastCGI 的多个子请求并发处理; SSL 和TLS SNI 支持; IMAP/POP3 代理服务功能: 使用外部 HTTP 认证服务器重定向用户到 IMAP/POP3 后端; 使用外部 HTTP 认证服务器认证用户后连接重定向到内部的SMTP 后端; 其他HTTP功能 基于名称和基于IP的虚拟服务器; Keep-alive and pipelined connections support;保持活动和支持管线连接; Flexible configuration;灵活的配置; Reconfiguration and online upgrade without interruption of the client processing;重构,未经客户处理中断在线升级;

Windows环境下的Nginx高并发实现

Software Development ? 软件开发 Electronic Technology & Software Engineering 电子技术与软件工程? 47 【关键词】Windows 服务器 Nginx 反向代理 高并发 1 引言 Nginx 是高性能的Http 和反向代理服务器,在Linux 环境下,其可以采用epoll 作为网络I/O 模型。在高并发连接的情况下,其是Apache 服务器不错的替代品。Nginx 具有高并 Windows 环境下的Nginx 高并发实现 文/岳晋 温宇 黄旻亮 发连接、内存占用低、成本低等特点。 Nginx 运行时,会存在一个主进程和多个工作进程。工作进程的数目可以在配置文件中进行指定,通常设置为CPU 的核数。主进程用于管理工作进程的运行,并处置工作进程的异常情况。借助于主进程和工作进程的模式,Nginx 可以实现平滑升级、配置即时生效等功能。而工作进程的任务相对单一,主要用于处理业务请求,它们彼此独立,互不影响。此外,借助于异步非阻塞的工作机制,Nginx 可以处理上万的并发请求。 反向代理是Nginx 的主要应用场景之一。 反向代理是相对于正向代理来说,一般情况下,内网的客户机通过代理服务器访问公网上服务的这种模式是正向代理。与此相反,当代理服务器的作用是将后台服务器隐藏起来,并根据客户机的请求,分发给后台服务器的这种方式是反向代理。Nginx 反向代理的原理如图1所示。 图1中,Nginx 代理服务器接收到来自客户端的请求,根据自己的配置,决定将该请求转发给哪个业务服务器。当业务服务器处理完 该请求后,将响应结果交给Nginx 代理服务器,Nginx 代理服务器再将响应内容返回给客户机。 反向代理可以保护后端服务器,此外,还可以用作负载均衡,来平衡后端服务器的性能压力。Nginx 通过proxy_pass 命令和upstream 模块,就可以实现反向代理。如果后台服务和Nginx 在同一机器上,但运行在不同的端口上,Nginx 可以将请求转发到后台服务运行的端口上。通常情况下,后台服务和Nginx 不在一台服务器上,这时候Nginx 可以将请求发送给upstream 模块,再通过upstream 模块转发给后台服务器。而且在upstream 模块中,也可以进行负载均衡相关的配置。 Nginx 的另一主要应用场景是负载均衡。负载均衡是在各服务器之间均衡业务压力,Nginx 的负载均衡策略包括轮询、指定权重、fair 、ip_hash 和url_hash 等。 2 Nginx性能调优相关配置 2.1 stub_status监控模块 得以提高。随着大量产品的借用,构件会趋于成熟,软件BOM 表也随之趋于成熟。这有利于同领域的其他产品借用或者部分借用。 对生产率的影响:一般来说,大约80%~90%的复用可使软件生产率提高25%~40%。 对成本的影响:软件复用率越高时,新研构件越少,耗费的人力成本和时间成本都会大大降低。 对管理的影响:在PDS 等系统中归档了的软件BOM 表,记录了关于该产品所用的所有软件构件的数据信息,如构件的名称、版本、基本内容、复用/新研等信息,以及构件与构件之间的嵌套关系。它对于质量管理中从最终产品追溯零件、组件起到关键作用。软件BOM 表以信息共享为基础,是综合管理、资源调度的重要依据。另外,软件BOM 表中复用/新研的数据也可作为安排软件开发计划的依据。 6 结束语 本文针对基于软件BOM 的构件化开发过 <<上接46页 程,阐述了软件BOM 的设计流程、设计形式及其应用价值。可以看出在构件化软件开发过程中,软件BOM 设计是不可缺少的重要环节。软件BOM 在“工厂”式的软件加工过程中起着连接设计与制造的纽带作用,对提高软件生产率和软件质量、降低软件开发成本都起着至关重要的作用。因此,做好软件需求分析、软件BOM 设计、构件设计、构件测试等,且每个环节都进行专家审核和评审,才能有效地提高软件开发的质量,推动软件工程的发展。 参考文献 [1]史济民.软件工程原理、方法与应用[M]. 北京:高等教育出版社,1990. [2]李航.基于通用试验体系结构支撑 平台的组件框架设计模式[J].软件,2013,34(5):85-87. [3]刘凤.基于软件构件技术的阮建华雷达 [J].现代雷达,2016(2). [4]STEPHEN M, WELBY P. Modular open s y s t e m s a r c h i t e c t u r e i n D o D acquisition[R]. Washington: DOPSR, 2014. [5]NELSON J A. Radar open system a r c h i t e c t u r e p r o v i d e s n e t centricity[J]. IEEE Aerospace and Electronic Systems Magazine, 2010, 25(10):17-20. [6]Wang Yongliang, Ding Qianjun, L i R o n g f e n g. A d a p t i v e A r r a y Processing[M]. Bejing: Tsinghua University Press, 2009. [7]Karl Wiegers, Joy Beatty.软件需求[M] 北京:清华大学出版社,2016,8-12.[8]莱芬韦尔,威德里格.软件需求管理: 统一化方法[M].北京:高等教育出版社,2002:18-21. 作者简介 王艳丽(1981-),女,硕士研究生。工程师。研究方向为雷达信号处理。 作者单位 南京电子技术研究所 江苏省南京市 210039

nginx 负载均衡宕机配置

1.摘要 (1)结论 详细描述了nginx记录失效节点的6种状态(time out、connect refuse、500、502、503、504,后四项5XX需要配置proxy_next_upstream中的状态才可以 生效)、失效节点的触发条件和节点的恢复条件、所有节点失效后nginx会进 行恢复并进行重新监听。 (2)Nginx 负载均衡方式介绍 Nginx的负载均衡方式一共有4种:rr(轮询模式)、ip_hash、fair、url_hash。(3)Ngxin负载均衡和相关反向代理配置内容 Nginx负载均衡和与容错相关的反向代理的配置。 (4)获取后端流程 后端server的自动容错流程图。 (5)测试环境和测试结果 针对几种错误方式进行自动容错测试。 2.结论 (1)nginx 判断节点失效状态 Nginx 默认判断失败节点状态以connect refuse和time out状态为准,不以HTTP错误状态进行判断失败,因为HTTP只要能返回状态说明该节点还可以正常连接,所以nginx判断其还是存活状态;除非添加了proxy_next_upstream指令设置对404、502、503、504、500和time out等错误进行转到备机处理,在next_upstream过程中,会对fails进行累加,如果备用机处理还是错误则直接返回错误信息(但404不进行 记录到错误数,如果不配置错误状态也不对其进行错误状态记录),综述,nginx记录错误数量只记录timeout 、connect refuse、502、500、503、504这6种状态,timeout和connect refuse是永远被记录错误状态,而502、500、503、504只有在配置proxy_next_upstream后nginx才会记录这4种HTTP错误到fails中,当fails大 于等于max_fails时,则该节点失效; (2)nginx 处理节点失效和恢复的触发条件 nginx可以通过设置max_fails(最大尝试失败次数)和fail_timeout(失效时间,在到达最大尝试失败次数后,在fail_timeout的时间范围内节点被置为失效,除非所 有节点都失效,否则该时间内,节点不进行恢复)对节点失败的尝试次数和失效时间 进行设置,当超过最大尝试次数或失效时间未超过配置失效时间,则nginx会对节点 状会置为失效状态,nginx不对该后端进行连接,直到超过失效时间或者所有节点都失效后,该节点重新置为有效,重新探测; (3)所有节点失效后nginx将重新恢复所有节点进行探测 如果探测所有节点均失效,备机也为失效时,那么nginx会对所有节点恢复为有效,重新尝试探测有效节点,如果探测到有效节点则返回正确节点内容,如果还是全 部错误,那么继续探测下去,当没有正确信息时,节点失效时默认返回状态为502,但是下次访问节点时会继续探测正确节点,直到找到正确的为止。

Nginx源代码分析

Nginx源代码分析 1.Nginx代码的目录和结构 nginx的源码目录结构层次明确,从自动编译脚本到各级的源码,层次都很清晰,是一个大型服务端软件构建的一个范例。以下是源码目录结构说明: ├─auto 自动编译安装相关目录 │├─cc 针对各种编译器进行相应的编译配置目录,包括Gcc、Ccc等 │├─lib 程序依赖的各种库,包括md5,openssl,pcre等 │├─os 针对不同操作系统所做的编译配置目录 │└─types ├─conf 相关配置文件等目录,包括nginx的配置文件、fcgi相关的配置等 ├─contrib ├─html index.html └─src 源码目录 ├─core 核心源码目录,包括定义常用数据结构、体系结构实现等 ├─event 封装的事件系统源码目录 ├─http http服务器实现目录 ├─mail 邮件代码服务器实现目录 ├─misc 该目录当前版本只包含google perftools包 └─os nginx对各操作系统下的函数进行封装以及实现核心调用的目录。2.基本数据结构 2.1.简单的数据类型 在core/ngx_config.h 目录里面定义了基本的数据类型的映射,大部分都映射到c语言自身的数据类型。 typedef intptr_t ngx_int_t; typedef uintptr_t ngx_uint_t; typedef intptr_t ngx_flag_t; 其中ngx_int_t,nginx_flag_t,都映射为intptr_t;ngx_uint_t映射为uintptr_t。 这两个类型在/usr/include/stdint.h的定义为: /* Types for `void *' pointers. */ #if __WORDSIZE == 64 # ifndef __intptr_t_defined

NginWEB服务器架构设计解决方案精修订

N g i n W E B服务器架构设计解决方案 集团标准化工作小组 #Q8QGGQT-GX8G08Q8-GNQGJ8-MHHGN#

Nginx是俄罗斯人编写的十分轻量级的HTTP服务器,Nginx,它的发音为“engine X”,是一个高性能的HTTP和反向代理服务器,同时也是一个IMAP/POP3/SMTP 代理服务器.Nginx是由俄罗斯人 Igor Sysoev 为俄罗斯访问量第二的站点开发的,它已经在该站点运行超过两年半了。Igor Sysoev在建立的项目时,使用基于BSD许可。 据说他当初是F5的成员之一,英文主页:。 俄罗斯的一些大网站已经使用它超过两年多了,一直表现不凡,相信想了解nginx的朋友都读过阿叶大哥的利用nginx实现负载均衡.直到2007年4月,俄罗斯大约有20%左右的虚拟主机是由nignx服务或代理的。Google在线安全博客中统计nginx服务或代理了大约所有Internet虚拟主机的 4%。而netcraft的统计显示,nginx服务的主机在过去的一年里以四倍的速度增长。短短的几年里,它的排名已跃进第9。(参见: Nginx以事件驱动的方式编写,所以有非常好的性能,同时也是一个非常高效的反向代理、负载平衡。其拥有匹配 Lighttpd的性能,同时还没有Lighttpd的内存泄漏问题,而且Lighttpd的mod_proxy也有一些问题并且很久没有更新。 因此我打算用其替代Apache应用于Linux服务器上。但是Nginx并不支持cgi方式运行,原因是可以减少因此带来的一些程序上的漏洞。那么我们必须使用FastCGI方式来执行PHP程序。 现在,Igor将源代码以类BSD许可证的形式发布。Nginx因为它的稳定性、丰富的模块库、灵活的配置和低系统资源的消耗而闻名.业界一致认为它是+mod_proxy_balancer的轻量级代替者,不仅是因为响应静态页面的速度非常快,而且它的模块数量达到Apache的近 2/3。对proxy 和 rewrite模块的支持很彻底,还支持mod_fcgi、ssl、vhosts ,适合用来做mongrel clusters的前端HTTP 响应。 nginx做为HTTP服务器,有以下几项基本特性: 处理静态文件,索引文件以及自动索引;打开文件描述符缓冲. 无缓存的反向代理加速,简单的负载均衡和容错. FastCGI,简单的负载均衡和容错. 模块化的结构。包括gzipping, byte ranges, chunked responses,以及 SSI-filter等filter。如果由FastCGI或其它代理服务器处理单页中存在的多个SSI,则这项处理可以并行运行,而不需要相互等待。 支持SSL 和 TLSSNI. Nginx专为性能优化而开发,性能是其最重要的考量,实现上非常注重效率。它支持内核Poll模型,能经受高负载的考验,有报告表明能支持高达 50,000个并发连接数。 Nginx具有很高的稳定性。其它HTTP服务器,当遇到访问的峰值,或者有人恶意发起慢速连接时,也很可能会导致服务器物理内存耗尽频繁交换,失去响应,只能重启服务器。例如当前apache一旦上到200个以上进程,web响应速度就明显非常缓慢了。而Nginx采取了分阶段资源分配技术,使得它的 CPU

win764位下配置http2nginxnodejs

最近要调研http2能给页面带来多少访问速度的提升,所以自己先搭一个环境测试一下; 一、CA数字证书: 要升级http2首先是要把http升级到https,https升级就需要CA证书,但由于现代的浏览器都已默认安装了一些网络证书,所以我们访问淘宝,京东之类的网站就不需要让用户自己安装了,其它没有安装的证书就得用户自己得去安装了; 现在网络上的很多https证书,有免费的也有付费的,但作为我是用于自己调试与测试用,当然找免费的了,但免费的证书需要申请与审核,时间也是得等,加上功能上也有限制,好吧,我是迫不及待的用证书,来调试,最后找到了OpenSSL,自己来创建证书,省去申请的时间,那现在就说说OpenSSL 如何创建一个ca证书,服务器证书与客户端证书; 安装准备: 下载OpenSSL我用的版本是openssl-1.1.0 下载安装ActivePerl最新版本即可; 下载安装nasm最新版本即可; 下载安装Visual Studio 2015 自己上度娘找吧,很多; 先把OpenSSL解压到E盘,目录名称为openssl-1.1.0; 点击开始按钮,选择Visual Studio Tools 下的64位编译机,定位到 E://openssl-1.1.0

输入命令: //初始化文件目录 $ perl Configure VC-WIN64A --prefix=E:/openssl-1.1.0/win64_OpenSSL --ope nssldir=E:/openssl-1.1.0/win64_SSL $ nmake $ nmake test

$ nmake install 注意,以上的安装方法一定要参考该版本的安装方法,这个安装方法的文件一般叫INSTALL,网上有很多方法,都是老版本来的; 生成密钥、证书 第一步,为服务器端和客户端准备公钥、私钥 # 生成服务器端私钥 genrsa -out server.key 1024 # 生成服务器端公钥 rsa -in server.key -pubout -out server.pem # 生成客户端私钥 genrsa -out client.key 1024 # 生成客户端公钥 rsa -in client.key -pubout -out client.pem 第二步,生成CA 证书 # 生成CA私钥 genrsa-out ca.key 1024 # X.509Certificate Signing Request (CSR) Management. req-config "E:\openssl-1.1.0\win64_SSL\https://www.wendangku.net/doc/b54999586.html,f" -new-key ca.key-o ut ca.csr # X.509Certificate Data Management.

Nginx源码分析

Nginx源代码分析 l00117893 1.Nginx代码的目录和结构 nginx的源码目录结构层次明确,从自动编译脚本到各级的源码,层次都很清晰,是一个大型服务端软件构建的一个范例。以下是源码目录结构说明: ├─auto 自动编译安装相关目录 │├─cc 针对各种编译器进行相应的编译配置目录,包括Gcc、Ccc等 │├─lib 程序依赖的各种库,包括md5,openssl,pcre等 │├─os 针对不同操作系统所做的编译配置目录 │└─types ├─conf 相关配置文件等目录,包括nginx的配置文件、fcgi相关的配置等 ├─contrib ├─html index.html └─src 源码目录 ├─core 核心源码目录,包括定义常用数据结构、体系结构实现等 ├─event 封装的事件系统源码目录 ├─http http服务器实现目录 ├─mail 邮件代码服务器实现目录 ├─misc 该目录当前版本只包含google perftools包 └─os nginx对各操作系统下的函数进行封装以及实现核心调用的目录。2.基本数据结构 2.1.简单的数据类型 在core/ngx_config.h 目录里面定义了基本的数据类型的映射,大部分都映射到c语言自身的数据类型。 typedef intptr_t ngx_int_t; typedef uintptr_t ngx_uint_t; typedef intptr_t ngx_flag_t; 其中ngx_int_t,nginx_flag_t,都映射为intptr_t;ngx_uint_t映射为uintptr_t。

高可用服务设计概述

高可用服务设计概述

1. 负载均衡与反向代理 当我们的应用单实例不能支撑用户请求时,就需要扩容,从一天服务器扩容到两台、几十台、几百台。然而用户访问时是通过如https://www.wendangku.net/doc/b54999586.html,的方式访问,在请求时,浏览器首先会查询DNS服务器获取对应的IP,然后通过此IP访问对应的服务。 对于负载均衡需要关心的几个方面如下: ?上游服务器配置:使用upstream server配置上游服务器。 ?负载均衡算法:配置多个上游服务器时的负载均衡机制。 ?失败重试机制:配置当超时或上游服务器不存活时,是否需要重试其他上游服务器。 ?服务器心跳检查:上游服务器的健康检查/心跳检查。 Nginx提供的负载均衡机制可以实现服务器的负载均衡、故障转移、失败重试、容错、健康检查等,当某些上游服务器出现问题时可以将请求转到其他上游服务器以保障高可用,并通过OpenResty实现更智能的负载均衡,如将热点与非热点流量分离、正常流量与爬虫流量分离等。Nginx负载均衡器本身也是一台反向代理服务器,将用户请求通过Ningx代理到内网中的某台上游服务器处理,反向代理服务器可以对响应结果进行缓存、压缩等处理以提升性能。

负载均衡算法 负载均衡算法用来解决用户请求到来时如何选择upstream server进行处理,默认采用的是round-robin (轮询),同时支持其他几种算法。 ?round-robin:轮询,默认负载均衡算法,即以轮询的方式将请求转发到上游服务器,通过配合weight配置可以实现基于权重的轮询。 ?ip-hash:根据客户IP进行负载均衡,即相同的IP将负载均衡到同一个upstream server。 ?hash key [consistent]:对某一个key进行哈希或者使用一致性哈希算法进行负载均衡。使用Hash算法那存在的问题是,当添加/删除一台服务器时,将导致很多key被重新负载均衡到不同的服务器(从而导致后端肯可能出现问题);因此,建议考虑使用一致性hash算法,这样当添加/删除一台服务器时,只有少数key将被重新负载均衡到不同的服务器。 ?哈希算法:此处是根据请求uri进行负载均衡,可以使用Nginx变量,因此可以实现复杂的算法。失败重试 当fail_timeout时间内失败了max_fails次请求,则认为该上游服务器不可用/不存活,然后将摘掉该上游服务器,fail_timeout时间后会再次将该服务器加入到存活上游服务器列表进行重试。

nginx学习总结

Nginx学习总结 Nginx概述及注意事项 ?nginx是一个高性能的 HTTP 和反向代理服务器,也是一个 IMAP/POP3/SMTP 代理服务 器。 ?目前Nginx使用简单的轮巡(polling)算法来实现负载均衡,所以无法做基本 链接计数的负载均衡。 ?目前官方 Nginx 并不支持 Windows,您只能在包括 Linux、UNIX、BSD 系统下安装和 使用; ?Nginx 本身只是一个 HTTP 和反向代理服务器,它无法像 Apache 一样通过安装各种模 块来支持不同的页面脚本,例如 PHP、CGI 等; ?Nginx 支持简单的负载均衡和容错; ?支持作为基本 HTTP 服务器的功能,例如日志、压缩、Byte ranges、Chunked responses、 SSL、虚拟主机等等,应有尽有。 Nginx优势 ?在高连接并发的情况下,Nginx是Apache服务器不错的替代品:Nginx在美国是 做虚拟主机生意的老板们经常选择的软件平台之一。能够支持高达 50,000 个并发连接数的响应,感谢Nginx为我们选择了epoll and kqueue作为开发模型。 ?Nginx作为负载均衡服务器:Nginx 既可以在内部直接支持Rails 和PHP 程序 对外进行服务,也可以支持作为HTTP代理服务器对外进行服务。Nginx采用C 进行编写,不论是系统资源开销还是CPU使用效率都比 Perlbal 要好很多。 ?作为邮件代理服务器:Nginx 同时也是一个非常优秀的邮件代理服务器(最早 开发这个产品的目的之一也是作为邮件代理服务器),Last. fm 描述了成功并且美妙的使用经验。 ?Nginx 是一个安装非常的简单,配置文件非常简洁(还能够支持perl语法), Bugs非常少的服务器:Nginx 启动特别容易,并且几乎可以做到7*24不间断运行,即使运行数个月也不需要重新启动。

相关文档