• w3cschoolNginx 使用手册


    https://www.w3cschool.cn/nginxsysc/

    Nginx 使用手册

    手册简介

    Nginx ("engine x") 是一个高性能的 HTTP 和 反向代理 服务器,也是一个 IMAP/POP3/SMTP 代理服务器 。 Nginx 是由 Igor Sysoev 为俄罗斯访问量第二的Rambler.ru 站点开发的,它已经在该站点运行超过四年多了。Igor 将源代码以类BSD许可证的形式发布。自Nginx 发布四年来,Nginx 已经因为它的稳定性、丰富的功能集、 示例配置文件和低系统资源的消耗而闻名了。目前国内各大门户网站已经部署了Nginx,如新浪、网易、腾讯

    手册说明

    201610251758148330

    官网:http://nginx.org/

    官方文档:http://nginx.org/en/docs/

    教程:http://www.w3cschool.cn/nginxsysc/gtxqwj.html

    下载:http://nginx.org/en/download.html

    Nginx是什么?

    Nginx ("engine x") 是一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP服务器。Nginx是由Igor Sysoev为俄罗斯访问量第二的Rambler.ru站点开发的,第一个公开版本0.1.0发布于2004年10月4日。其将源代码以类BSD许可证的形式发布,因它的稳定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名。2011年6月1日,nginx 1.0.4发布。

    Nginx是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like 协议下发行。由俄罗斯的程序设计师Igor Sysoev所开发,供俄国大型的入口网站及搜索引擎Rambler(俄文:Рамблер)使用。其特点是占有内存少,并发能力强,事实上nginx的并发能力确实在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。

    Nginx有什么优点?

    Nginx 可以在大多数 Unix like OS 上编译运行,并有 Windows 移植版。 Nginx 的1.4.0稳定版已经于2013年4月24日发布,一般情况下,对于新建站点,建议使用最新稳定版作为生产版本,已有站点的升级急迫性不高。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代码完全用C语言从头写成,已经移植到许多体系结构和操作系统,包括:Linux、FreeBSD、Solaris、Mac OS X、AIX以及Microsoft Windows。Nginx有自己的函数库,并且除了zlib、PCRE和OpenSSL之外,标准模块只使用系统C库函数。而且,如果不需要或者考虑到潜在的授权冲突,可以不使用这些第三方库。

    代理服务器

    作为邮件代理服务器:Nginx 同时也是一个非常优秀的邮件代理服务器(最早开发这个产品的目的之一也是作为邮件代理服务器),Last.fm 描述了成功并且美妙的使用经验。

    Nginx 是一个安装非常的简单、配置文件非常简洁(还能够支持perl语法)、Bug非常少的服务器。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 后端;

    • 认证方法:

    • POP3: POP3 USER/PASS, APOP, AUTH LOGIN PLAIN CRAM-MD5;

    • IMAP: IMAP LOGIN;

    • SMTP: AUTH LOGIN PLAIN CRAM-MD5;

    • SSL 支持;

    • 在 IMAP 和 POP3 模式下的 STARTTLS 和 STLS 支持;

    __支持的操作系统:__

    • FreeBSD 3.x, 4.x, 5.x, 6.x i386; FreeBSD 5.x, 6.x amd64;

    • Linux 2.2, 2.4, 2.6 i386; Linux 2.6 amd64;

    • Solaris 8 i386; Solaris 9 i386 and sun4u; Solaris 10 i386;

    • MacOS X (10.4) PPC;

    • windows 编译版本支持 windows 系列操作系统;

    __结构与扩展:__

    • 一个主进程和多个工作进程,工作进程运行于非特权用户;

    • kqueue (FreeBSD 4.1+), epoll (Linux 2.6+), rt signals (Linux 2.2.19+), /dev/poll (Solaris 7 11/99+), select, 以及 poll 支持;

    • kqueue支持的不同功能包括 EV_CLEAR, EV_DISABLE (临时禁止事件), NOTE_LOWAT, EV_EOF, 有效数据的数目,错误代码;

    • sendfile (FreeBSD 3.1+), sendfile (Linux 2.2+), sendfile64 (Linux 2.4.21+), 和 sendfilev (Solaris 8 7/01+) 支持;

    • 输入过滤 (FreeBSD 4.1+) 以及 TCP_DEFER_ACCEPT (Linux 2.4+) 支持;

    • 10,000 非活动的 HTTP keep-alive 连接仅需要 2.5M 内存。

    • 最小化的数据拷贝操作;

    __其他HTTP功能:__

    • 基于IP 和名称的虚拟主机服务;

    • Memcached 的 GET 接口;

    • 支持 keep-alive 和管道连接;

    • 灵活简单的配置;

    • 重新配置和在线升级而无须中断客户的工作进程;

    • 可定制的访问日志,日志写入缓存,以及快捷的日志回卷;

    • 4xx-5xx 错误代码重定向;

    • 基于 PCRE 的 rewrite 重写模块;

    • 基于客户端 IP 地址和 HTTP 基本认证的访问控制;

    • PUT, DELETE, 和 MKCOL 方法;

    • 支持 FLV (Flash 视频);

    • 带宽限制;

    __实验特性:__

    • 内嵌的 perl

    • 通过 aio_read()/aio_write() 的套接字工作的实验模块,仅在 FreeBSD 下。

    • 对线程的实验化支持,FreeBSD 4.x 的实现基于 rfork()

    为什么选择Nginx

    Nginx 是一个很牛的高性能Web和反向代理服务器, 它具有有很多非常优越的特性:

    • 在高连接并发的情况下,Nginx是Apache服务器不错的替代品: Nginx在美国是做虚拟主机生意的老板们经常选择的软件平台之一. 能够支持高达 50,000 个并发连接数的响应, 感谢Nginx为我们选择了 epoll and kqueue 作为开发模型.

    • Nginx作为负载均衡服务器: Nginx 既可以在内部直接支持 Rails 和 PHP 程序对外进行服务, 也可以支持作为 HTTP代理 服务器对外进行服务. Nginx采用C进行编写, 不论是系统资源开销还是CPU使用效率都比 Perlbal 要好很多.

    • 作为邮件代理服务器: Nginx 同时也是一个非常优秀的邮件代理服务器(最早开发这个产品的目的之一也是作为邮件代理服务器), Last.fm 描述了成功并且美妙的使用经验.

    • Nginx 是一个 [#installation 安装] 非常的简单 , 配置文件 非常简洁(还能够支持perl语法), Bugs 非常少的服务器: Nginx 启动特别容易, 并且几乎可以做到7*24不间断运行,即使运行数个月也不需要重新启动. 你还能够 不间断服务的情况下进行软件版本的升级 .

    运行和控制 Nginx - 命令行参数和信号

    nginx命令行参数

    不像许多其他软件系统,Nginx 仅有几个命令行参数,完全通过配置文件来配置

    • -c </path/to/config> 为 Nginx 指定一个配置文件,来代替缺省的。
    • -t 不运行,而仅仅测试配置文件。nginx 将检查配置文件的语法的正确性,并尝试打开配置文件中所引用到的文件。
    • -v 显示 nginx 的版本。
    • -V 显示 nginx 的版本,编译器版本和配置参数。

    nginx 控制信号

    可以使用信号系统来控制主进程。默认,nginx 将其主进程的 pid 写入到 ​/usr/local/nginx/nginx.pid​ 文件中。通过传递参数给 ./configure 或使用 pid 指令,来改变该文件的位置。

    nginx 启动、停止、重启命令

    nginx启动

    sudo /usr/local/nginx/nginx    

     (nginx二进制文件绝对路径,可以根据自己安装路径实际决定)

    nginx从容停止命令,等所有请求结束后关闭服务

    ps -ef |grep nginx
    kill -QUIT  nginx 主进程号 

    nginx 快速停止命令,立刻关闭 nginx 进程

    ps -ef |grep nginx
    kill -TERM nginx 主进程号  

    如果以上命令不管用,可以强制停止

    kill -9 nginx主进程号 

    如果嫌麻烦可以不用查看进程号,直接使用命令进行操作

    其中​/usr/local/nginx/nginx.pid 为nginx.conf​中 ​pid ​命令设置的参数,用来存放 nginx 主进程号的文件

    kill -信号类型(HUP|TERM|QUIT) `cat /usr/local/nginx/nginx.pid` 

    例如

    kill -QUIT `cat /usr/local/nginx/nginx.pid`

    nginx重启命令

    nginx重启可以分成几种类型

    1.简单型,先关闭进程,修改你的配置后,重启进程。

    kill -QUIT `cat /usr/local/nginx/nginx.pid`
    sudo /usr/local/nginx/nginx

    2.重新加载配置文件,不重启进程,不会停止处理请求

    3.平滑更新nginx二进制,不会停止处理请求

    优化 Nginx

    hash表

    Ngnix使用hash表来协助完成请求的快速处理。

    考虑到保存键及其值的hash表存储单元的大小不至于超出设定参数(hash bucket size), 在启动和每次重新配置时,Nginx为hash表选择尽可能小的尺寸。

    直到hash表超过参数(hash max size)的大小才重新进行选择. 对于大多数hash表都有指令来修改这些参数。例如,保存服务器名字的hash表是由指令server_names_hash_max_size 和 server_names_hash_bucket_size所控制的。参数hash bucket size总是等于hash表的大小,并且是一路处理器缓存大小的倍数。在减少了在内存中的存取次数后,使在处理器中加速查找hash表键值成为可能。如果hash bucket size等于一路处理器缓存的大小,那么在查找键的时候,最坏的情况下在内存中查找的次数为2。第一次是确定存储单元的地址,第二次是在存储单元中查找键值。因此,如果Nginx给出需要增大 hash max size 或 hash bucket size的提示,那么首要的是增大前一个参数的大小.

    事件模型

    Nginx支持如下处理连接的方法(I/O复用方法),这些方法可以通过use指令指定。

    • select - 标准方法。 如果当前平台没有更有效的方法,它是编译时默认的方法。你可以使用配置参数 --with-select_module 和 --without-select_module 来启用或禁用这个模块。

    • poll - 标准方法。 如果当前平台没有更有效的方法,它是编译时默认的方法。你可以使用配置参数 --with-poll_module 和 --without-poll_module 来启用或禁用这个模块。

    • kqueue - 高效的方法,使用于 FreeBSD 4.1+, OpenBSD 2.9+, NetBSD 2.0 和 MacOS X. 使用双处理器的MacOS X系统使用kqueue可能会造成内核崩溃。

    • epoll - 高效的方法,使用于Linux内核2.6版本及以后的系统。在某些发行版本中,如SuSE 8.2, 有让2.4版本的内核支持epoll的补丁。

    • rtsig - 可执行的实时信号,使用于Linux内核版本2.2.19以后的系统。默认情况下整个系统中不能出现大于1024个POSIX实时(排队)信号。这种情况对于高负载的服务器来说是低效的;所以有必要通过调节内核参数 /proc/sys/kernel/rtsig-max 来增加队列的大小。可是从Linux内核版本2.6.6-mm2开始, 这个参数就不再使用了,并且对于每个进程有一个独立的信号队列,这个队列的大小可以用 RLIMIT_SIGPENDING 参数调节。当这个队列过于拥塞,nginx就放弃它并且开始使用 poll 方法来处理连接直到恢复正常。

    • /dev/poll - 高效的方法,使用于 Solaris 7 11/99+, HP/UX 11.22+ (eventport), IRIX 6.5.15+ 和 Tru64 UNIX 5.1A+.

    • eventport - 高效的方法,使用于 Solaris 10. 为了防止出现内核崩溃的问题, 有必要安装 这个 安全补丁。

    Nginx rewrite配置

    Nginx以其良好的并发性能,目前正在逐渐取代Apache成为大家的Web server首选,但是Nginx目前的中文资料很少,需要大家努力贡献。

    下面我介绍一下Nginx的Rewrite模块设置及Wordpress和Discuz的示例。Nginx的Rewrite规则比Apache的简单灵活多了,从下面介绍可见一斑。

    首先,Nginx可以用if进行条件匹配,语法规则类似C,举例如下:

    if ($http_user_agent ~ MSIE) {
    rewrite  ^(.*)$  /msie/$1  break;
    }

    Nginx正则匹配符说明

    1、正则表达式匹配,其中:

    * ~  为区分大小写匹配
    * ~* 为不区分大小写匹配
    * !~和!~*分别为区分大小写不匹配及不区分大小写不匹配

    2、文件及目录匹配,其中:

    * -f和!-f用来判断是否存在文件
    * -d和!-d用来判断是否存在目录
    * -e和!-e用来判断是否存在文件或目录
    * -x和!-x用来判断文件是否可执行

    如:

    if (!-f $request_filename) {
    proxy_pass  http://127.0.0.1;
    }

    Nginx全局变量

    一些可用的全局变量有,可以用做条件判断(待补全)

    1.$args
    2.$content_length
    3.$content_type
    4.$document_root
    5.$document_uri
    6.$host
    7.$http_user_agent
    8.$http_cookie
    9.$limit_rate
    10.$request_body_file
    11.$request_method
    12.$remote_addr
    13.$remote_port
    14.$remote_user
    15.$request_filename
    16.$request_uri
    17.$query_string
    18.$scheme
    19.$server_protocol
    20.$server_addr
    21.$server_name
    22.$server_port
    23.$uri

    其次,Nginx的Rewrite规则与Apache几乎完全一致,所不同的是最后的flag标记,举例如下:

    rewrite ^/feed/$ http://feed.shunz.net last;

    flag标记有:

    * last 相当于Apache里的[L]标记,表示完成rewrite,不再匹配后面的规则
    * break 与last类似
    * redirect 返回302临时重定向
    * permanent 返回301永久重定向

    常用几个Nginx rewrite配置实例:

    Wordpress的重定向规则:

    if (!-e $request_filename) {
    rewrite ^/(index|atom|rsd)\.xml$ http://feed.shunz.net last;
    rewrite ^([_0-9a-zA-Z-]+)?(/wp-.*) $2 last;
    rewrite ^([_0-9a-zA-Z-]+)?(/.*\.php)$ $2 last;
    rewrite ^ /index.php last;
    }

    Discuz!的重定向规则:

    if (!-f $request_filename) {
    rewrite ^/archiver/((fid|tid)-[\w\-]+\.html)$   /archiver/index.php?$1 last;
    rewrite ^/forum-([0-9]+)-([0-9]+)\.html$   /forumdisplay.php?fid=$1&page=$2 last;
    rewrite ^/thread-([0-9]+)-([0-9]+)-([0-9]+)\.html$  /viewthread.php?tid=$1&extra=page%3D$3&page=$2 last;
    rewrite ^/space-(username|uid)-(.+)\.html$   /space.php?$1=$2 last;
    rewrite ^/tag-(.+)\.html$ /tag.php?name=$1 last;
    }

    多目录转成参数 

    要求:abc.domian.com/sort/2 => abc.domian.com/index.php?act=sort&name=abc&id=2 

    规则配置:

    if ($host ~* (.*)\.domain\.com) { 

        set $sub_name $1;

        rewrite ^/sort\/(\d+)\/?$ /index.php?act=sort&cid=$sub_name&id=$1 last; 

    目录对换 

    要求:/123456/xxxx -> /xxxx?id=123456 

    规则配置:

    rewrite ^/(\d+)/(.+)/ /$2?id=$1 last; 

    再来一个针对浏览器优化的自动rewrite,这里rewrite后的目录可以是存在的;

    例如设定nginx在用户使用ie的使用重定向到/nginx-ie目录

    规则如下:

     if ($http_user_agent ~ MSIE) {

         rewrite ^(.*)$ /nginx-ie/$1 break; 

    目录自动加“/” ,这个功能一般浏览器自动完成

    if (-d $request_filename){ 

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

    以下这些可能就跟广义的rewrite重写无关了

    禁止htaccess 

    location ~/\.ht { 

        deny all; 

    禁止多个目录 

    location ~ ^/(cron|templates)/ { 

        deny all; break; 

    禁止以/data开头的文件,可以禁止/data/下多级目录下.log.txt等请求

    location ~ ^/data { 

        deny all; 

    Nginx 主模块

    这里是控制 Nginx 的基本功能的指令.

    指令

    • [#daemon daemon]

    • [#debug_points debug_points]

    • [#error_log error_log]

    • [#include include]

    • [#lock_file lock_file]

    • [#master_process master_process]

    • [#pid pid]

    • [#ssl_engine ssl_engine]

    • [#timer_resolution timer_resolution]

    • [#user user group]

    • [#worker_cpu_affinity worker_cpu_affinity]

    • [#worker_priority worker_priority]

    • [#worker_processes worker_processes]

    • [#worker_rlimit_core worker_rlimit_core]

    • [#worker_rlimit_nofile worker_rlimit_nofile]

    • [#worker_rlimit_sigpending worker_rlimit_sigpending]

    • [#working_directory working_directory]

    daemon

    语法: daemon on | off

    缺省值: on

    daemon  off;

    Do not use the "daemon" and "master_process" directives in a production mode, these options are mainly used for development only. You can use daemon offsafely in production mode with runit / daemontools however you can't do a graceful upgrade. master_process off should never be used in production.

    生产环境中不要使用"daemon"和"master_process"指令,这些选项仅用于开发调试。

    debug_points

    语法: debug_points [stop | abort]

    缺省值: none

    debug_points stop;

    There are some assertion points inside nginx that allow to stop nginx to attach the debugger, or to abort and to create the core file.

    应该适用于调试,在调试器内设置断点之类的。

    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 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;

    Do not use the "daemon" and "master_process" directives in a production mode, these options are mainly used for development only.

    生产环境中不要使用"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

    Here you can set your preferred openssl engine if any available. You can figure out which one do you have with the commandline tool:

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

    openssl engine -t

    例如:

    $ openssl engine -t
    (cryptodev) BSD cryptodev engine
    : [ available ] 
    (dynamic) Dynamic engine loading support
    : [ unavailable ]

    timer_resolution

    语法: timer_resolution t

    缺省值: none

    Example:

    timer_resolution  100ms;

    The directive allows to decrease number gettimeofday() syscalls. By default gettimeofday() is called after each return from kevent(), epoll, /dev/poll, select(), poll().

    But if you need an exact time in logs when logging $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 0001 0010 0100 1000;

    Bind each worker process to one CPU only.

    分别给每个worker进程绑定一个CPU.

    worker_proceses     2;
    worker_cpu_affinity 0101 1010;

    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进程,原因如下:

    1. to use SMP

    2. to decrease latency when workers blockend on disk I/O

    3. 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 缺省值: '

    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) Specifies 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 absolute paths only, all relative paths in configuration files are relative to --prefix==PATH.

    Nginx 事件模块

    摘要

    设置Nginx处理连接请求

    指令

    accept_mutex

    Syntax: accept_mutex [ on | off ]

    Default: on

    nginx 使用连接互斥锁进行顺序的accept()系统调用.

    accept_mutex_delay

    Syntax: accept_mutex_delay Nms;

    Default: 500ms

    如果一个进程没有互斥锁,它将延迟至少多长时间。默认情况下,延迟是500ms 。

    debug_connection

    Syntax: debug_connection [ip | CIDR]

    Default: none

    Since 0.3.54 this option support CIDR address format

    This option gives you the ability to write debug log only for the clients of this IP/NET.

    Several different directives are possible.

    Example:

    error_log /var/log/nginx/errors;events {debug_connection   192.168.1.1;}

    devpoll_changes

    devpoll_events

    kqueue_changes

    kqueue_events

    epoll_events

    Syntax: devpoll_changes

    Default:

    These directives specify how many events may be passed to/from kernel, using appropriate method.

    The default devpoll values are 32, the rest are 512.

    multi_accept

    Syntax: multi_accept [ on | off ]

    Default: off

    multi_accept tries to accept() as many connections as possible after nginx gets notification about a new connection.

    rtsig_signo

    Syntax: rtsig_signo

    Default:

    nginx uses two signals when the rtsig method is used. The directive specified the first signal number. The second is plus 1.

    By default rtsig_signo is SIGRTMIN+10 (40).

    rtsig_overflow_events

    rtsig_overflow_test

    rtsig_overflow_threshold

    Syntax: rtsig_overflow_*

    Default:

    These directives specifies how to handle rtsig queue overflows. When overflow occurred nginx flushes rtsig queue, then it handles events switching between poll() and rtsig. poll() handles consecutively all unhandled events, while rtsig periodicaly drains queue to prevent a new overflow. When overflow is handled completely, nginx switches to rtsig method again.

    The rtsig_overflow_events specifies the number of events to be passed via poll(). The default is 16.

    The rtsig_overflow_test specifies after which number of events handled by poll() nginx will drains rtsig queue. The default is 32.

    The rtsig_overflow_threshold works in Linux 2.4.x only. Before to drain rtsig queue nginx looks in a kernel how the queue is filled up

    The default is 1/10. "rtsig_overflow_threshold 3" means 1/3.

    use

    Syntax: use [ kqueue | rtsig | epoll | /dev/poll | select | poll | eventport ]

    Default:


    如果在./configure的时候指定了不止一种事件模型,那么可以设置其中一个,以便告诉nginx使用哪种事件模型。默认情况下nginx会在./configure时找出最适合系统的事件模型。

    你可以在 这里 查看可用的事件模型以及如何在./configure时激活

    worker_connections

    Syntax: worker_connections number

    Default:

    通过worker_connections和worker_proceses可以计算出maxclients:

    max_clients = worker_processes * worker_connections

    作为反向代理,max_clients为:

    max_clients = worker_processes * worker_connections/4

    Since a browser opens 2 connections by default to a server and nginx uses the fds (file descriptors) from the same pool to connect to the upstream backend

    Nginx HTTP FastCGI 模块

    摘 要

    这个模块允许 Nginx 与 FastCGI 进程交互,并通过传递参数来控制 FastCGI 进程工作。

    配置实例:

    location / {
      fastcgi_pass   localhost:9000;
      fastcgi_index  index.php;
    
      fastcgi_param  SCRIPT_FILENAME  /home/www/scripts/php$fastcgi_script_name;
      fastcgi_param  QUERY_STRING     $query_string;
      fastcgi_param  REQUEST_METHOD   $request_method;
      fastcgi_param  CONTENT_TYPE     $content_type;
      fastcgi_param  CONTENT_LENGTH   $content_length;
    }

    语法:

    fastcgi_buffers

    syntax: fastcgi_buffers the_number is_size;
    
    default: fastcgi_buffers 84k/8k;
    
    context: http, server, location
    
    该指令集设置缓冲区的数量和大小,用于缓存从 FastCGI Server 接收到的数据。默认情况下,一个缓冲区的大小相当于一个页面的大小。根据平台的不同设置为4K/8K

    fastcgi_buffer_size

    语法: fastcgi_buffer_size 大小

    默认: fastcgi_buffer_size 4k / 8k

    环境: http, server, location

    该命令设置缓冲区大小,其中将读取第一部分的输出,从 fastcgi 服务端获取

    在这个输出的小输出标头部分的位置,作为一项规则

    默认情况下,缓冲区大小是等于一个 fastcgi 缓冲区大小,允许将其设置为更少

    fastcgi_cache

    syntax: fastcgi_cache zone;

    default: none

    context: http, server, location

    设置缓存在共享内存中的名称. 一块区域可以被用于不用的地方.

    fastcgi_cache_key

    syntax: fastcgi_cache_key line ;

    default: none

    context: http, server, location

    设置缓存的 key , 例:

    fastcgi_cache_key localhost: 9000 $ request_uri;

    fastcgi_cache_methods

    语法: fastcgi_cache_methods [GET HEAD POST];

    默认: fastcgi_cache_methods GET HEAD;

    环境: main, http, location

    GET / HEAD 语法糖, 也就是. 即使你刚刚设置,也无法禁用 GET / HEAD

    fastcgi_cache_methods  POST;

    fastcgi_cache_min_uses

    syntax: fastcgi_cache_min_uses n

    default: fastcgi_cache_min_uses 1

    context: http, server, location

    TODO: Description.

    fastcgi_cache_path

    syntax: fastcgi_cache_path /path/to/cache [levels=m:n keys_zone=name:time inactive=time clean_time=time]

    default: none

    context: http, server, location

    TODO: Description.

    fastcgi_cache_use_stale

    syntax: fastcgi_cache_use_stale [updating|error|timeout|invalid_header|http_500]
    
    default: fastcgi_cache_use_stale off;
    
    context: http, server, location
    
    TODO: Description.

    fastcgi_cache_valid

    syntax: fastcgi_cache_valid [http_error_code|time]
    
    default: none
    
    context: http, server, location
    
    TODO: Description.

    fastcgi_index

    syntax: fastcgi_index file
    
    default: none
    
    context: http, server, location
    
    The name of the file which will be appended to the URI and stored in the variable $fastcgi_script_name if URI concludes with a slash.

    fastcgi_hide_header

    syntax: fastcgi_hide_header name
    
    context: http, server, location
    
    默认情况下Nginx 不会从FastCGI 进程里给客户端发送"Status" 和"X-Accel-..." 消息头。这个指令可以用来掩饰别的headers 。
    
    如果需要"Status" 和"X-Accel-..." 消息头,那就需要使用这个指令让FastCGI 强制发送消息头给客户端。

    fastcgi_ignore_client_abort

    syntax: fastcgi_ignore_client_abort on|off
    
    default: fastcgi_ignore_client_abort off
    
    context: http, server, location
    
    这个指令用来决定忽略用户取消的请求。

    fastcgi_intercept_errors

    syntax: fastcgi_intercept_errors on|off
    
    default: fastcgi_intercept_errors off
    
    context: http, server, location
    
    这个指令用来决定是否要把客户端转向4xx和5xx错误页,或允许Nginx自动指定错误页页。
    
    注意:你需要在此明确错误页,它才是有用的。Igor 曾说:“如果没有定制的处理机制,Nginx不会拦截一个没有缺省页的错误。Nginx 只会拦截一些小的错误,放过其他一些。

    fastcgi_param

    syntax: fastcgi_param parameter value
    
    default: none
    
    context: http, server, location
    
    该指令指定的参数,将被传递给FastCGI-server。
    
    它可能使用字符串、变量及其它们的组合来作为参数值。如果不在此制定参数,它就会继承外层设置;如果在此设置了参数,将清除外层相关设置,仅启用本层设置。
    
    下面是一个例子,对于PHP来说的最精简的必要参数:
    
      fastcgi_param  SCRIPT_FILENAME  /home/www/scripts/php$fastcgi_script_name;
      fastcgi_param  QUERY_STRING     $query_string;
    
    参数SCRIPT_FILENAME 是PHP 用来确定执行脚本的名字,而参数QUERY_STRING 是它的一个子参数。
    
    如果要处理POST,那么这三个附加参数是必要的:
    
      fastcgi_param  REQUEST_METHOD   $request_method;
      fastcgi_param  CONTENT_TYPE     $content_type;
      fastcgi_param  CONTENT_LENGTH   $content_length;
    
    如果PHP 在编译时使用了--enable-force-cgi-redirect选项,设置参数REDIRECT_STATUS 的值为200就是必须的了。
    
      fastcgi_param  REDIRECT_STATUS  200;

    Nginx 限制并发

    在Nginx服务器上进行一些常规设置,来限制其并发数及会话空间等。

    nginx限制ip并发数,也是说限制同一个ip同时连接服务器的数量

    1,添加limit_conn_zone

    这个变量只能在http使用

    http{
      ...
      #定义一个名为one的limit_zone,大小10M内存来存储session,
      #以$binary_remote_addr 为key
      #nginx 1.18以后用limit_conn_zone替换了limit_conn
      #且只能放在http作用域
      limit_conn_zone $binary_remote_addr zone=one:10m;
    

    2,添加limit_conn

    这个变量可以在http, server, location使用
    只限制一个站点,所以添加到server里面

    server{
        ...
        location {
          ...
           limit_conn one 20;		  #连接数限制
           #带宽限制,对单个连接限数,如果一个ip两个连接,就是500x2k
           limit_rate 500k;		 
          ...
        }
        ...
      }
    

    3,重启nginx

    service nginx restart
    #或者重新加载 /usr/local/nginx/sbin/nginx -s reload

    Nginx 限制IP访问频率

    在Nginx服务器上进行一些常规设置,限制某一段时间内同一ip访问数实例.

    nginx限制ip访问频率数,也是说限制同一个ip在一段时间里连接服务器的次数.

    通过这种设置,可以一定程度上防止类似CC这种快速频率请求的攻击

    1,添加limit_req_zone

    这个变量只能在http使用

    http{
      ...
      #定义一个名为allips的limit_req_zone用来存储session,大小是10M内存,
      #以$binary_remote_addr 为key,限制平均每秒的请求为5个,
      #1M能存储16000个状态,rete的值必须为整数,
      #如果限制两秒钟一个请求,可以设置成30r/m
      limit_req_zone $binary_remote_addr zone=allips:10m rate=5r/s;
      ...

    2,添加limit_req

    这个变量可以在http, server, location使用
    只限制一个站点,所以添加到server里面

     ...
      server{
        ...
        location {
          ...
          #限制每ip每秒不超过20个请求,漏桶数burst为5
          #brust的意思就是,如果第1秒、2,3,4秒请求为19个,
          #第5秒的请求为25个是被允许的。
          #但是如果你第1秒就25个请求,第2秒超过20的请求返回503错误。
          #nodelay,如果不设置该选项,严格使用平均速率限制请求数,
          #第1秒25个请求时,5个请求放到第2秒执行,
          #设置nodelay,25个请求将在第1秒执行。
          limit_req zone=allips burst=5 nodelay;
          ...
        }
        ...
      }
      ...

    3,重启nginx

    service nginx restart
    #或者重新加载 /usr/local/nginx/sbin/nginx -s reload

    Nginx 限制IP带宽占用

    nginx 限速模块

    在Nginx服务器上进行一些常规设置,来限制其并发数及会话空间等。

    nginx限制ip并发数,也是说限制同一个ip同时连接服务器的数量;

    通过配合限制并发下的流量限制,可以一定程度上限制单ip带宽占用

    1,添加limit_conn_zone

    这个变量只能在http使用

    http{
      ...
      #定义一个名为one的limit_zone,大小10M内存来存储session,
      #以$binary_remote_addr 为key
      #nginx 1.18以后用limit_conn_zone替换了limit_conn
      #且只能放在http作用域
      limit_conn_zone $binary_remote_addr zone=one:10m;
    

    2,添加limit_conn,limit_rate

    这两个变量可以在http, server, location使用
    只限制一个站点,所以添加到server里面

    limit_conn one 2; #限制每个IP只能发起两个并发连接。

    limit_rate 300k; #对每个连接限速300k。

    注意,这里是对连接限速,而不是对IP限速。
    如果一个IP允许两个并发连接,那么这个IP就是限速limit_rate×limit_conn。比如 300k × 2 就是对ip的流量带宽控制

    示例:

    server{
        ...
        location {
          ...
           limit_conn one 2;		  #连接数限制
           #带宽限制,对单个连接限数,如果一个ip两个连接,就是300x2 k
           limit_rate 300k;		 
          ...
        }
        ...
      }

    Nginx 配置SSL及Http跳转到Https

    随着微信小程序和appstore对ssl安全的需求,越来越多的网站和app需要支持SSL功能,需要开启https的方式来打开网站或传输数据。

    ssl证书网上可以找到收费和免费的申请,nginx配置如下:

    Nginx配置SSL并把Http跳转到Https,需要修改Nginx.conf配置文件:

    #原80端口做301转跳
    server {
        listen 80;
        server_name w3cschool.cn www.w3cschool.cn;
        return 301 https://www.zhimiyun.com$request_uri;    #跳转到Https
    }#配置ssl证书和开启ssl功能
    server {
        listen       443;
        server_name  www.w3cschool.cn;
        root   wwwroot;
        index  index.html index.htm;
    
        ssl                  on;
        ssl_certificate      /usr/ssl/ca.pem; #证书地址
        ssl_certificate_key  /usr/ssl/ca.key;
    
        ssl_session_timeout  5m;
    
        ssl_protocols  SSLv2 SSLv3 TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers  ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
        ssl_prefer_server_ciphers   on;
        error_page 497 "https://$host$uri?$args"; #这是跳转Http请求到Https
    
        location / {
            ...
        }
    }

    也就是再添加一个虚拟机server,80端口一个,443端口一个。

    但是有些程序只会给你往端口上转发,不会自动修正http为https,这样的程序还不少,例如phpmyadmin:

    遇到这样的程序我们需要修改Nginx.conf配置文件,在443的server的fastcgi字段中添加一个语句:

    fastcgi_param HTTPS on; #attention!#
    
    例如:
    location ~ .*\.(php|php5)?$
                {
                    try_files $uri =404;
                    fastcgi_pass  unix:/tmp/php-cgi.sock;
                    fastcgi_index index.php;
                    fastcgi_param HTTPS on; #attention!#
                    include fcgi.conf;
                }
    
    注释:

    把http重定向到https使用了nginx的重定向命令。那么应该如何写重定向?之前老版本的nginx可能使用了以下类似的格式。 

    rewrite ^/(.*)$ http://domain.com/$1 permanent;

    或者

    rewrite ^ http://domain.com$request_uri? permanent;

    现在nginx新版本已经换了种写法,上面这些已经不再推荐。现在网上可能还有很多文章写的是第一种。

    新的写法比较推荐方式是:
    return 301 http://domain.com$request_uri;

    Nginx 静态资源缓存设置

    在开发调试web的时候,经常会碰到因浏览器缓存(cache)而经常要去清空缓存或者强制刷新来测试的烦恼,提供下apache不缓存配置和nginx不缓存配置的设置。在常用的缓存设置里面有两种方式,都是使用add_header来设置:分别为Cache-Control和Pragma。

    nginx:
    location ~ .*\.(css|js|swf|php|htm|html )$ {
    add_header Cache-Control no-store;add_header Pragma no-cache;
    }
    对于站点中不经常修改的静态内容(如图片,JS,CSS),可以在服务器中设置expires过期时间,控制浏览器缓存,达到有效减小带宽流量,降低服务器压力的目的。

    以Nginx服务器为例:

     location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
    #过期时间为30天,
    #图片文件不怎么更新,过期可以设大一点,
    #如果频繁更新,则可以设置得小一点。
    expires 30d;
    }
    
    location ~ .*\.(js|css)$ {
    expires 10d;
    } 

    背景】:Expires是Web服务器响应消息头字段,在响应http请求时告诉浏览器在过期时间前浏览器可以直接从浏览器缓存取数据,而无需再次请求。

    相关资料
    1、Cache-control策略
    Cache-Control与Expires的作用一致,都是指明当前资源的有效期,控制浏览器是否直接从浏览器缓存取数据还是重新发请求到服务器取数据。只不过Cache-Control的选择更多,设置更细致,如果同时设置的话,其优先级高于Expires。

    http协议头Cache-Control :
    值可以是public、private、no-cache、no- store、no-transform、must-revalidate、proxy-revalidate、max-age
    各个消息中的指令含义如下:

    • Public指示响应可被任何缓存区缓存。
    • Private指示对于单个用户的整个或部分响应消息,不能被共享缓存处理。这允许服务器仅仅描述当用户的部分响应消息,此响应消息对于其他用户的请求无效。
    • no-cache指示请求或响应消息不能缓存
    • no-store用于防止重要的信息被无意的发布。在请求消息中发送将使得请求和响应消息都不使用缓存。
    • max-age指示客户机可以接收生存期不大于指定时间(以秒为单位)的响应。
    • min-fresh指示客户机可以接收响应时间小于当前时间加上指定时间的响应。
    • max-stale指示客户机可以接收超出超时期间的响应消息。如果指定max-stale消息的值,那么客户机可以接收超出超时期指定值之内的响应消息。

    Last-Modified/If-Modified-Since

    • Last-Modified/If-Modified-Since要配合Cache-Control使用。
    • Last-Modified:标示这个响应资源的最后修改时间。web服务器在响应请求时,告诉浏览器资源的最后修改时间。
    • If-Modified-Since:当资源过期时(使用Cache-Control标识的max-age),发现资源具有Last-Modified声明,则再次向web服务器请求时带上头 If-Modified-Since,表示请求时间。web服务器收到请求后发现有头If-Modified-Since 则与被请求资源的最后修改时间进行比对。若最后修改时间较新,说明资源又被改动过,则响应整片资源内容(写在响应消息包体内),HTTP 200;若最后修改时间较旧,说明资源无新修改,则响应HTTP 304 (无需包体,节省浏览),告知浏览器继续使用所保存的cache。
     

    其最终达到的就是等效于设置这三类html缓存技术:

    <meta http-equiv="pragma" content="no-cache"/>
    <meta http-equiv="Cache-Control" content="no-cache, must-revalidate"/> 
    <meta http-equiv="expires" content="0"/>
  • 相关阅读:
    java.lang.RuntimeException: HRegionServer Aborted的问题
    Solr 读数据流程
    Solr 写数据流程
    solr索引创建流程
    Solr 倒排索引
    Solr 核心组成
    Solr的关键特性
    poj3308 Paratroopers --- 最小点权覆盖-&gt;最小割
    YII 路由配置
    MySQL具体解释(5)-----------函数超全总结
  • 原文地址:https://www.cnblogs.com/hanease/p/16062761.html
Copyright © 2020-2023  润新知