nginx笔记

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

nginx tar.gz 源码安装

    yum install  cmake bison bison-devel ncurses-devel libaio-devel perl
    首先由于nginx的一些模块依赖一些lib库,所以在安装nginx之前,必须先安装这些lib库,这些依赖库主要有g++、gcc、openssl-devel、pcre-devel和zlib-devel 所以执行如下命令安装
    find -name nginx  
    yum remove nginx  
    wget http://nginx.org/download/nginx-1.7.4.tar.gz
    tar -zxvf nginx-1.7.4.tar.gz  
        $   yum install gcc-c++  
        $   yum install pcre pcre-devel  
        $   yum install zlib zlib-devel  
        $   yum install openssl openssl--devel  
     接下来安装,使用--prefix参数指定nginx安装的目录,make、make install安装
     cd  nginx-1.7.4
        $   ./configure  $默认安装在/usr/local/nginx --prefix=/usr/local/nginx$默认安装在/usr/local/nginx   
        $   make  
        $   make install     
    ./configure --prefix=/home/server/nginx
    启动操作

    /usr/nginx/sbin/nginx (/usr/nginx/sbin/nginx -t 查看配置信息是否正确)

nginx yum安装
    如果你带有yum,可以直接yum remove xxx
    如果是rpm包,rpm -e xxx
    yum remove nginx
    rpm -e nginx
    下载对应当前系统版本的nginx包(package)
#wget http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
    建立nginx的yum仓库
    # yum -ivh nginx-release-centos-7-0.el7.ngx.noarch.rpm
    3下载并安装nginx
    # yum install nginx
    4启动nginx服务
    systemctl start nginx
    5配置
    默认的配置文件在 /etc/nginx 路径下,使用该配置已经可以正确地运行nginx;如需要自定义,修改其下的 nginx.conf 等文件即可。

CENTOS 6.5 配置YUM安装NGINX
    From:https://my.oschina.net/VincentJiang/blog/224993
    第一步,在/etc/yum.repos.d/目录下创建一个源配置文件nginx.repo:
    cd /etc/yum.repos.d/
    vim nginx.repo
    填写如下内容:
    [nginx]
    name=nginx repo
    baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
    gpgcheck=0
    enabled=1
    保存,则会产生一个/etc/yum.repos.d/nginx.repo文件。
    下面直接执行如下指令即可自动安装好Nginx:
    yum install nginx -y
    安装完成,下面直接就可以启动Nginx了:
    /etc/init.d/nginx start
    Nginx的命令以及配置文件位置:
    /etc/init.d/nginx start # 启动Nginx服务
    /etc/init.d/nginx stop # 停止Nginx服务
    /etc/nginx/nginx.conf # Nginx配置文件位置

    Nginx的命令以及配置文件位置:
    /etc/init.d/nginx start # 启动Nginx服务
    /etc/init.d/nginx stop # 停止Nginx服务
    /etc/nginx/nginx.conf # Nginx配置文件位置
    现在Nginx已经启动了,直接访问服务器就能看到Nginx欢迎页面了的。

    如果还无法访问,则需配置一下Linux防火墙。
    iptables -I INPUT 5 -i eth0 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
    service iptables save
    service iptables restart
    至此,Nginx已经全部配置安装完成。
    

ubuntu 彻底删除并安装nginx
    http://blog.csdn.net/u010571844/article/details/50819704
    1.先执行一下命令:
    1.1 删除nginx,–purge包括配置文件
    sudo apt-get --purge remove nginx
    1.2 自动移除全部不使用的软件包
    sudo apt-get autoremove
    1.3 罗列出与nginx相关的软件
    dpkg --get-selections|grep nginx
    nginx                       install
    nginx-common                    install
    nginx-core                  install
    1.4 删除1.3查询出与nginx有关的软件
    sudo apt-get --purge remove nginx
    sudo apt-get --purge remove nginx-common
    sudo apt-get --purge remove nginx-core
    这样就可以完全卸载掉nginx包括配置文件
    2.查看nginx正在运行的进程,如果有就kill掉
    ps -ef |grep nginx
    看下nginx还有没有启动,一般执行完1后,nginx还是启动着的,如下:
    stephen@stephen-OptiPlex-390:~$ ps -ef |grep nginx
    root      7875  2317  0 15:02 ?        00:00:00 nginx    master process /usr/sbin/nginx
    www-data  7876  7875  0 15:02 ?        00:00:00 nginx    worker process
    www-data  7877  7875  0 15:02 ?        00:00:00 nginx    worker process
    www-data  7878  7875  0 15:02 ?        00:00:00 nginx    worker process
    www-data  7879  7875  0 15:02 ?        00:00:00 nginx    worker process
    stephen   8321  3510  0 15:20 pts/0    00:00:00 grep --color=auto nginx
    3.kill nginx进程
    sudo kill  -9  7875 7876 7877 7879
    4.全局查找与nginx相关的文件
    sudo  find  /  -name  nginx*
    5.依依删除4列出的所有文件
    sudo rm -rf file
    这样就彻底删除nginx了
    6. 再次重装
    sudo apt-get update
    sudo apt-get install nginx

中文文档网站
www.nginx.cn/doc/index.html 如下文档出自下面此网站
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;
__结构与扩展:__
    一个主进程和多个工作进程。工作进程是单线程的,且不需要特殊授权即可运行;
    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 主要的英语站点是 http://sysoev.ru/en/
英语文档草稿由 Aleksandar Lazic 完成 点击 。

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

作为 Web 服务器:相比 Apache,Nginx 使用更少的资源,支持更多的并发连接,体现更高的效率,这点使 Nginx 尤其受到虚拟主机提供商的欢迎。能够支持高达 50,000 个并发连接数的响应,感谢 Nginx 为我们选择了 epoll and kqueue 作为开发模型.

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

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

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

Nginx安装
nginx可以使用各平台的默认包来安装,本文是介绍使用源码编译安装,包括具体的编译参数信息。
正式开始前,编译环境gcc g++ 开发库之类的需要提前装好,这里默认你已经装好。
ububtu平台编译环境可以使用以下指令
apt-get install build-essential
apt-get install libtool
centos平台编译环境使用如下指令
安装make:
yum -y install gcc automake autoconf libtool make
安装g++:
yum install gcc gcc-c++
下面正式开始
---------------------------------------------------------------------------
一般我们都需要先装pcre, zlib,前者为了重写rewrite,后者为了gzip压缩。
1.选定源码目录
可以是任何目录,本文选定的是/usr/local/src
cd /usr/local/src
2.安装PCRE库
ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/ 下载最新的 PCRE 源码包,使用下面命令下载编译和安装 PCRE 包:
cd /usr/local/src
wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.34.tar.gz
tar -zxvf pcre-8.34.tar.gz
cd pcre-8.34
./configure
make
make install
3.安装zlib库
http://zlib.net/zlib-1.2.8.tar.gz 下载最新的 zlib 源码包,使用下面命令下载编译和安装 zlib包:
cd /usr/local/src

wget http://zlib.net/zlib-1.2.8.tar.gz
tar -zxvf zlib-1.2.8.tar.gz
cd zlib-1.2.8
./configure
make
make install
4.安装ssl(某些vps默认没装ssl)
cd /usr/local/src
wget http://www.openssl.org/source/openssl-1.0.1c.tar.gz
tar -zxvf openssl-1.0.1c.tar.gz
5.安装nginx
Nginx 一般有两个版本,分别是稳定版和开发版,您可以根据您的目的来选择这两个版本的其中一个,下面是把 Nginx 安装到 /usr/local/nginx 目录下的详细步骤:
cd /usr/local/src
wget http://nginx.org/download/nginx-1.4.2.tar.gz
tar -zxvf nginx-1.4.2.tar.gz
cd nginx-1.4.2

./configure --sbin-path=/usr/local/nginx/nginx \
--conf-path=/usr/local/nginx/nginx.conf \
--pid-path=/usr/local/nginx/nginx.pid \
--with-http_ssl_module \
--with-pcre=/usr/local/src/pcre-8.34 \
--with-zlib=/usr/local/src/zlib-1.2.8 \
--with-openssl=/usr/local/src/openssl-1.0.1c

make
make install
--with-pcre=/usr/src/pcre-8.34 指的是pcre-8.34 的源码路径。
--with-zlib=/usr/src/zlib-1.2.7 指的是zlib-1.2.7 的源码路径。
安装成功后 /usr/local/nginx 目录下如下
fastcgi.conf            koi-win             nginx.conf.default
fastcgi.conf.default    logs                scgi_params
fastcgi_params          mime.types          scgi_params.default
fastcgi_params.default  mime.types.default  uwsgi_params
html                    nginx               uwsgi_params.default
koi-utf                 nginx.conf          win-utf
6.启动
确保系统的 80 端口没被其他程序占用,运行/usr/local/nginx/nginx 命令来启动 Nginx,
netstat -ano|grep 80
如果查不到结果后执行,有结果则忽略此步骤(ubuntu下必须用sudo启动,不然只能在前台运行)
sudo /usr/local/nginx/nginx
打开浏览器访问此机器的 IP,如果浏览器出现 Welcome to nginx! 则表示 Nginx 已经安装并运行成功。
 
-----------------------------------------------------
到这里nginx就安装完成了,如果只是处理静态html就不用继续安装了
如果你需要处理php脚本的话,还需要安装php-fpm。
下面安装排错
附:可能遇到的错误和一些帮助信息
1.1编译pcre错误
libtool    compile    unrecognized option `-DHAVE_CONFIG_H'
libtool    compile    Try `libtool --help' for more information.
make[1]    *** [pcrecpp.lo] Error 1
make[1]    Leaving directory `/usr/local/src/pcre-8.34'
make    *** [all] Error 2
 
解决办法:安装g++,别忘了重新configure
apt-get install g++
apt-get install build-essential
make clean
./configure
make
1.2 make出错
make    *** No rule to make target `build', needed by `default'.  Stop.
./configure    error    SSL modules require the OpenSSL library.
You can either do not enable the modules, or install the OpenSSL library
into the system, or build the OpenSSL library statically from the source
with nginx by using --with-openssl= option.
按照第4步的安装方法或
ubuntu下
apt-get install openssl
apt-get install libssl-dev
centos下
yum -y install openssl openssl-devel
2.nginx编译选项
make是用来编译的,它从Makefile中读取指令,然后编译。
make install是用来安装的,它也从Makefile中读取指令,安装到指定的位置。
configure命令是用来检测你的安装平台的目标特征的。它定义了系统的各个方面,包括nginx的被允许使用的连接处理的方法,比如它会检测你是不是有CC或GCC,并不是需要CC或GCC,它是个shell脚本,执行结束时,它会创建一个Makefile文件。nginx的configure命令支持以下参数:
    --prefix=path    定义一个目录,存放服务器上的文件 ,也就是nginx的安装目录。默认使用 /usr/local/nginx。
    --sbin-path=path 设置nginx的可执行文件的路径,默认为  prefix/sbin/nginx.
    --conf-path=path  设置在nginx.conf配置文件的路径。nginx允许使用不同的配置文件启动,通过命令行中的-c选项。默认为prefix/conf/nginx.conf.
    --pid-path=path  设置nginx.pid文件,将存储的主进程的进程号。安装完成后,可以随时改变的文件名 , 在nginx.conf配置文件中使用 PID指令。默认情况下,文件名 为prefix/logs/nginx.pid.
    --error-log-path=path 设置主错误,警告,和诊断文件的名称。安装完成后,可以随时改变的文件名 ,在nginx.conf配置文件中 使用 的error_log指令。默认情况下,文件名 为prefix/logs/error.log.
    --http-log-path=path  设置主请求的HTTP服务器的日志文件的名称。安装完成后,可以随时改变的文件名 ,在nginx.conf配置文件中 使用 的access_log指令。默认情况下,文件名 为prefix/logs/access.log.
    --user=name  设置nginx工作进程的用户。安装完成后,可以随时更改的名称在nginx.conf配置文件中 使用的 user指令。默认的用户名是nobody。
    --group=name  设置nginx工作进程的用户组。安装完成后,可以随时更改的名称在nginx.conf配置文件中 使用的 user指令。默认的为非特权用户。
    --with-select_module --without-select_module 启用或禁用构建一个模块来允许服务器使用select()方法。该模块将自动建立,如果平台不支持的kqueue,epoll,rtsig或/dev/poll。
    --with-poll_module --without-poll_module 启用或禁用构建一个模块来允许服务器使用poll()方法。该模块将自动建立,如果平台不支持的kqueue,epoll,rtsig或/dev/poll。
    --without-http_gzip_module — 不编译压缩的HTTP服务器的响应模块。编译并运行此模块需要zlib库。
    --without-http_rewrite_module  不编译重写模块。编译并运行此模块需要PCRE库支持。
    --without-http_proxy_module — 不编译http_proxy模块。
    --with-http_ssl_module — 使用https协议模块。默认情况下,该模块没有被构建。建立并运行此模块的OpenSSL库是必需的。
    --with-pcre=path — 设置PCRE库的源码路径。PCRE库的源码(版本4.4 - 8.30)需要从PCRE网站下载并解压。其余的工作是Nginx的./ configure和make来完成。正则表达式使用在location指令和 ngx_http_rewrite_module 模块中。
    --with-pcre-jit —编译PCRE包含“just-in-time compilation”(1.1.12中, pcre_jit指令)。
    --with-zlib=path —设置的zlib库的源码路径。要下载从 zlib(版本1.1.3 - 1.2.5)的并解压。其余的工作是Nginx的./ configure和make完成。ngx_http_gzip_module模块需要使用zlib 。
    --with-cc-opt=parameters — 设置额外的参数将被添加到CFLAGS变量。例如,当你在FreeBSD上使用PCRE库时需要使用:--with-cc-opt="-I /usr/local/include。.如需要需要增加 select()支持的文件数量:--with-cc-opt="-D FD_SETSIZE=2048".
    --with-ld-opt=parameters —设置附加的参数,将用于在链接期间。例如,当在FreeBSD下使用该系统的PCRE库,应指定:--with-ld-opt="-L /usr/local/lib".
典型实例(下面为了展示需要写在多行,执行时内容需要在同一行)
./configure
    --sbin-path=/usr/local/nginx/nginx
    --conf-path=/usr/local/nginx/nginx.conf
    --pid-path=/usr/local/nginx/nginx.pid
    --with-http_ssl_module
    --with-pcre=../pcre-4.4
    --with-zlib=../zlib-1.1.3

运行和控制Nginx
nginx命令行参数
不像许多其他软件系统,Nginx 仅有几个命令行参数,完全通过配置文件来配置
-c 为 Nginx 指定一个配置文件,来代替缺省的。
-t 不运行,而仅仅测试配置文件。nginx 将检查配置文件的语法的正确性,并尝试打开配置文件中所引用到的文件。
-v 显示 nginx 的版本。
-V 显示 nginx 的版本,编译器版本和配置参数。
 
nginx控制信号
可以使用信号系统来控制主进程。默认,nginx 将其主进程的 pid 写入到 /usr/local/nginx/nginx.pid 文件中。通过传递参数给 ./configure 或使用 pid 指令,来改变该文件的位置。
主进程可以处理以下的信号:
TERM, INT    快速关闭
QUIT    从容关闭
HUP    重载配置
用新的配置开始新的工作进程
从容关闭旧的工作进程
USR1    重新打开日志文件
USR2    平滑升级可执行程序。
WINCH    从容关闭工作进程
尽管你不必自己操作工作进程,但是,它们也支持一些信号:
TERM, INT    快速关闭
QUIT    从容关闭
USR1    重新打开日志文件
 
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 支持几个信号,能在它运行时控制其操作。其中最普通的是 15 ,用来中止运行的进程:
# ps aux | egrep '(PID|nginx)'
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root      2213  0.0  0.0   6784  2036 ?        Ss   03:01   0:00 nginx    master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
# kill -15 2213
而最有趣的是能平滑改变 nginx 配置的选项(请注意,在重载前,要先测试一下配置文件):
 
# nginx -t -c /etc/nginx/nginx.conf
2006/09/16 13:07:10 [info] 15686#0    the configuration file /etc/nginx/nginx.conf syntax is ok
2006/09/16 13:07:10 [info] 15686#0    the configuration file /etc/nginx/nginx.conf was tested successfully
# ps aux | egrep '(PID|nginx)'
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root      2213  0.0  0.0   6784  2036 ?        Ss   03:01   0:00 nginx    master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
# kill -HUP 2213
当 nginx 接收到 HUP 信号,它会尝试先解析配置文件(如果指定配置文件,就使用指定的,否则使用默认的),成功的话,就应用新的配置文件(例如:重新打开日志文件或监听的套接 字)。之后,nginx 运行新的工作进程并从容关闭旧的工作进程。通知工作进程关闭监听套接字但是继续为当前连接的客户提供服务。所有客户端的服务完成后,旧的工作进程被关闭。 如果新的配置文件应用失败,nginx 将继续使用旧的配置进行工作。
 
平滑升级到新的二进制代码
你可以在不中断服务的情况下 - 新的请求也不会丢失,使用新的 nginx 可执行程序替换旧的(当升级新版本或添加/删除服务器模块时)。
首先,使用新的可执行程序替换旧的(最好做好备份),然后,发送 USR2 (kill -USR2 pid)信号给主进程。主进程将重命名它的 .pid 文件为 .oldbin (比如:/usr/local/nginx/logs/nginx.pid.oldbin),然后执行新的可执行程序,依次启动新的主进程和新的工作进程:
 
  PID  PPID USER    %CPU   VSZ WCHAN  COMMAND
33126     1 root     0.0  1164 pause  nginx    master process /usr/local/nginx/sbin/nginx
33134 33126 nobody   0.0  1368 kqread nginx    worker process (nginx)
33135 33126 nobody   0.0  1380 kqread nginx    worker process (nginx)
33136 33126 nobody   0.0  1368 kqread nginx    worker process (nginx)
36264 33126 root     0.0  1148 pause  nginx    master process /usr/local/nginx/sbin/nginx
36265 36264 nobody   0.0  1364 kqread nginx    worker process (nginx)
36266 36264 nobody   0.0  1364 kqread nginx    worker process (nginx)
36267 36264 nobody   0.0  1364 kqread nginx    worker process (nginx)
在这时,两个 nginx 实例会同时运行,一起处理输入的请求。要逐步停止旧的实例,你必须发送 WINCH 信号给旧的主进程,然后,它的工作进程就将开始从容关闭:
 
  PID  PPID USER    %CPU   VSZ WCHAN  COMMAND
33126     1 root     0.0  1164 pause  nginx    master process /usr/local/nginx/sbin/nginx
33135 33126 nobody   0.0  1380 kqread nginx    worker process is shutting down (nginx)
36264 33126 root     0.0  1148 pause  nginx    master process /usr/local/nginx/sbin/nginx
36265 36264 nobody   0.0  1364 kqread nginx    worker process (nginx)
36266 36264 nobody   0.0  1364 kqread nginx    worker process (nginx)
36267 36264 nobody   0.0  1364 kqread nginx    worker process (nginx)
一段时间后,旧的工作进程处理了所有已连接的请求后退出,就仅由新的工作进程来处理输入的请求了:
 
  PID  PPID USER    %CPU   VSZ WCHAN  COMMAND
33126     1 root     0.0  1164 pause  nginx    master process /usr/local/nginx/sbin/nginx
36264 33126 root     0.0  1148 pause  nginx    master process /usr/local/nginx/sbin/nginx
36265 36264 nobody   0.0  1364 kqread nginx    worker process (nginx)
36266 36264 nobody   0.0  1364 kqread nginx    worker process (nginx)
36267 36264 nobody   0.0  1364 kqread nginx    worker process (nginx)
这时,因为旧的服务器还尚未关闭它监听的套接字,所以,通过下面的几步,你仍可以恢复旧的服务器:
    发送 HUP 信号给旧的主进程 - 它将在不重载配置文件的情况下启动它的工作进程
    发送 QUIT 信号给新的主进程,要求其从容关闭其工作进程
    发送 TERM 信号给新的主进程,迫使其退出
    如果因为某些原因新的工作进程不能退出,向其发送 KILL 信号
新的主进程退出后,旧的主进程会由移除 .oldbin 前缀,恢复为它的 .pid 文件,这样,一切就都恢复到升级之前了。
如果尝试升级成功,而你也希望保留新的服务器时,发送 QUIT 信号给旧的主进程使其退出而只留下新的服务器运行:
 
      PID  PPID USER    %CPU   VSZ WCHAN  COMMAND
    36264     1 root     0.0  1148 pause  nginx    master process /usr/local/nginx/sbin/nginx
    36265 36264 nobody   0.0  1364 kqread nginx    worker process (nginx)
    36266 36264 nobody   0.0  1364 kqread nginx    worker process (nginx)
    36267 36264 nobody   0.0  1364 kqread nginx    worker process (nginx)
配置符号参考
容量符号缩写
k,K    千字节
m,M    兆字节
例如, "8k", "1m" 代表字节数计量.
时间符号缩写
ms    毫秒
s    秒
m    分钟
h    小时
d    日
w    周
M    一个月, 30天
y    年, 365 天
例如, "1h 30m", "1y 6M". 代表 "1小时 30分", "1年零6个月".
优化 Nginx
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. 为了防止出现内核崩溃的问题, 有必要安装 这个 安全补丁。

常见问题(FAQ)
    [#notwork 某些东东不工作 (URL重写, 代理, 路径, ...)]
    [#other 有没有其它类似的Web服务器]
    [#chroot 对于chroot的支持是否在计划之中?]
    [#usecase 在什么情况下使用Nginx比使用squid要好?]
    [#imapexample 有没有人能给出一个完整的.conf配置文件来详细的解读一下怎么配置和测试 IMAP 模块, 而不只是关于 IMAP 的只言片语啊?]
    [#smtpexample 怎么让Nginx成为以postfix做为后端的SMTP代理?]
    [#loadbalancing Nginx使用什么算法来实现负载均衡? 它能实现基于连接数的负载均衡吗?]
    [#proxy_buffering 我能关闭从代理服务器到后端服务器的缓存吗或者使用上传进度特性?]
某些东东不工作 (URL重写, 代理, 路径, ...)
例如: 如URL重写(rewrite)不工作了或者是unix的路径(/$PATH)的问题云云...
请仔细阅读 [NginxDebugging] 并且 逐行 查看错误日志。
如果你没找到错误 打起精神 试着到IRC或邮件列表里说明一下你碰到的问题。
有没有其它类似的Web服务器
    Cherokee
    Lighttpd (Lighty)
    thttpd
关于各自的优缺点请使用自己喜欢的搜索引挚查找  ;-)
对于chroot的支持是否在计划之中?
有人知道吗?
在什么情况下使用Nginx比使用squid要好? 反之亦然。
大体上来说nginx主要用于反向加速代理而不是像squid那样做为常规代理服务器。Nginx的最大优势在于高负载情况下内存和CPU的低消耗。 我不认为squid能给你带来比nginx更好的性能。
怎么让Nginx成为以postfix做为后端的SMTP代理?
有人知道不?
Nginx使用什么算法来实现负载均衡? 它能实现基于连接数的负载均衡吗?
目前Nginx使用简单的轮巡算法,所以无法做基本链接计数的负载均衡。 这个可能会在将来的版本中有所改变。
> 我能关闭从代理服务器到后端服务器的缓存吗或者使用上传进度特性?
基于 太多人询问下面的问题:
    我能为了得到上传进度而关闭代理的缓存吗
    使用nginx我怎么才能给用户显示上传进度
    ...
到目前为止 (2007-Apr-26) 还没有办法关闭到后端服务器的缓存.
调试 nginx
Nginx的一个 杀手级特性 就是你能使用 debug_connection 指令只调试 某些 连接。
这个设置只有是你使用 --with-debug 编译的nginx才有效。
nginx在windows上的安装
写一下简单的安装方法
1.下载软件
需要的软件有nginx,php,mysql(如不需要可不安装)
nginx.org,www.php.net上面有得下
全部解压出来
php基本不用做任何修改(下载直接解压版本的)
2.配置nginx
只需修改一行(nginx/conf/nginx.conf)
  fastcgi_param  SCRIPT_FILENAME  d:/nginx/html/$fastcgi_script_name;
找到大概这一行修改路径最好是绝对路径(相对路径可以自行探讨)
3.运行软件
先运行php
程序》运行》cmd
到php所在目录运行下面代码
php-cgi.exe -b 127.0.0.1:9000 -c php\php.ini
再运行nginx
到nginx所在目录
nginx.exe -c conf\nginx.conf
这样就ok了。

win下可以使用NPMserv更强大

by afen.cn
nginx在ubuntu上的安装
1、安装Nginx
apt-get install nginx
(要最新版本下载下来编译吧)
装完应该能正常运行了。如果之前有装APACHE要改下端口。。。或者直接
apt-get remove apache2
/etc/init.d/nginx stop
/etc/init.d/nginx start
2、安装php-cgi
apt-get install php-cgi
(要自定义安装的编译吧)
3、改php-cgi的配置
Ubuntu下是/etc/php5/cgi/php.ini
之前有安装过php的话会复制apache的配置文件
打开cgi.fix_pathinfo选项:
cgi.fix_pathinfo=1;
4、改Nginx的fastcgi传递参数
Ubuntu下是/etc/nginx/fastcgi_params
默认应该已经设置好了,内容差不多就下面那样:
代码: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_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param DOCUMENT_URI $document_uri;
fastcgi_param DOCUMENT_ROOT $document_root;
fastcgi_param SERVER_PROTOCOL $server_protocol;
fastcgi_param GATEWAY_INTERFACE CGI/1.1;
fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;
fastcgi_param REMOTE_ADDR $remote_addr;
fastcgi_param REMOTE_PORT $remote_port;
fastcgi_param SERVER_ADDR $server_addr;
fastcgi_param SERVER_PORT $server_port;
fastcgi_param SERVER_NAME $server_name;
# PHP only, required if PHP was built with –enable-force-cgi-redirect
fastcgi_param REDIRECT_STATUS 200;
5、创建VHost配置(这里只说Ubuntu下的,也就路径和包含文件目录的区别了)
在/etc/nginx/sites-available/下创建服务器配置文件比如myserver
ln -n /etc/nginx/sites-available/myserver /etc/nginx/sites-enabled/myserver
其实懒的话直接创建在enabled里也没问题-。-
内容填:
代码:server {
listen 80;
server_name myserver.com;
access_log /var/log/nginx/myserver.access.log;
location / {
root /wwwroot/myserver;
index index.php;
autoindex off;
}
location ~ \.php$ {
include /etc/nginx/fastcgi_params;
fastcgi_param SCRIPT_FILENAME /wwwroot/myserver/$fastcgi_script_name;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
}
# redirect server error pages to the static page /50x.html
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /var/www/nginx-default;
}
# deny access to .htaccess files, if Apache’s document root
location ~ /\.ht {
deny all;
}
}
6、安装spawn-fcgi
下载可到这里,这东西已经独立出来了
http://redmine.lighttpd.net/projects/spawn-fcgi/wiki
下完后解压编译
sudo ./configure –prefix=/usr/local
sudo make
sudo make install
7、启动spaw-fcgi
sudo spawn-fcgi -a 127.0.0.1 -p 9000 -u www-data -g www-data -f /usr/bin/php5-cgi -F 10
哦,对后面10进程不爽的人可以取消或是加到100
8、重启Nginx
/etc/init.d/nginx restart
9、定义下hosts就可以看结果啦
编辑/etc/hosts加入
127.0.0.1 myserver.com
然后打开浏览器就可以看结果啦~
有问题欢迎指出~~
完整例子
两个虚拟主机(纯静态-html 支持) - Two Virtual Hosts, Serving Static Files
http {
    server {
    listen          80;
    server_name     www.domain1.com;
    access_log      logs/domain1.access.log main;
    location / {
    index index.html;
    root  /var/www/domain1.com/htdocs;
    }
    }
    server {
    listen          80;
    server_name     www.domain2.com;
    access_log      logs/domain2.access.log main;
    location / {
    index index.html;
    root  /var/www/domain2.com/htdocs;
    }
    }
}
虚拟主机标准配置(简化) - A Default Catchall Virtual Host
http {
    server {
    listen          80 default;
    server_name     _ *;
    access_log      logs/default.access.log main;
    location / {
    index index.html;
    root  /var/www/default/htdocs;
    }
    }
}
在父文件夹中建立子文件夹以指向子域名 - Wildcard Subdomains in a Parent Folder
这是一个添加子域名(或是当DNS已指向服务器时添加一个新域名)的简单方法。需要注意的是,我已经将FCGI配置进该文件了。如果你只想使服务器为静态文件服务,可以直接将FCGI配置信息注释掉,然后将默认主页文件变成index.html。
这个简单的方法比起为每一个域名建立一个 vhost.conf 配置文件来讲,只需要在现有的配置文件中增加如下内容:
This is just a really easy way to keep adding new subdomains, or to add new domains automatically when DNS records are pointed at the server. Note that I have included FCGI here as well. If you want to just serve static files, strip out the FCGI config and change the default document to index.html. Rather than creating a new vhost.conf file for every domain, just create one of these:
server {
    # Replace this port with the right one for your requirements
    # 根据你的需求改变此端口
    listen       80;  #could also be 1.2.3.4:80 也可以是1.2.3.4:80的形式
    # Multiple hostnames seperated by spaces.  Replace these as well.
    # 多个主机名可以用空格隔开,当然这个信息也是需要按照你的需求而改变的。
    server_name  star.yourdomain.com *.yourdomain.com www.*.yourdomain.com;
    #Alternately    _ *
    #或者可以使用:_ * (具体内容参见本维基其他页面)
    root /PATH/TO/WEBROOT/$host;
    error_page  404              http://yourdomain.com/errors/404.html;
    access_log  logs/star.yourdomain.com.access.log;
    location / {
    root   /PATH/TO/WEBROOT/$host/;
    index  index.php;
    }
    # serve static files directly
    # 直接支持静态文件 (从配置上看来不是直接支持啊)
    location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico|html)$ {
    access_log        off;
    expires           30d;
    }
    location ~ .php$ {
    # By all means use a different server for the fcgi processes if you need to
    # 如果需要,你可以为不同的FCGI进程设置不同的服务信息
    fastcgi_pass   127.0.0.1:YOURFCGIPORTHERE;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  /PATH/TO/WEBROOT/$host/$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_intercept_errors on;
    }
    location ~ /\.ht {
    deny  all;
    }
    }

Nginx官方网站例子
#!nginx
    # 使用的用户和组
    user  www www;
    # 指定工作衍生进程数
    worker_processes  2;
    # 指定 pid 存放的路径
    pid /var/run/nginx.pid;

    # [ debug | info | notice | warn | error | crit ]
    # 可以在下方直接使用 [ debug | info | notice | warn | error | crit ]  参数
    error_log  /var/log/nginx.error_log  info;

    events {
    # 允许的连接数
    connections   2000;
    # use [ kqueue | rtsig | epoll | /dev/poll | select | poll ] ;
    # 具体内容查看 http://wiki.codemongers.com/事件模型
    use kqueue;
    }

    http {
    include       conf/mime.types;
    default_type  application/octet-stream;

    log_format main      '$remote_addr - $remote_user [$time_local]  '
    '"$request" $status $bytes_sent '
    '"$http_referer" "$http_user_agent" '
    '"$gzip_ratio"';

    log_format download  '$remote_addr - $remote_user [$time_local]  '
    '"$request" $status $bytes_sent '
    '"$http_referer" "$http_user_agent" '
    '"$http_range" "$sent_http_content_range"';

    client_header_timeout  3m;
    client_body_timeout    3m;
    send_timeout           3m;

    client_header_buffer_size    1k;
    large_client_header_buffers  4 4k;

    gzip on;
    gzip_min_length  1100;
    gzip_buffers     4 8k;
    gzip_types       text/plain;

    output_buffers   1 32k;
    postpone_output  1460;

    sendfile         on;
    tcp_nopush       on;
    tcp_nodelay      on;
    send_lowat       12000;

    keepalive_timeout  75 20;

    #lingering_time     30;
    #lingering_timeout  10;
    #reset_timedout_connection  on;


    server {
    listen        one.example.com;
    server_name   one.example.com  www.one.example.com;

    access_log   /var/log/nginx.access_log  main;

    location / {
    proxy_pass         http://127.0.0.1/;
    proxy_redirect     off;

    proxy_set_header   Host             $host;
    proxy_set_header   X-Real-IP        $remote_addr;
    #proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;

    client_max_body_size       10m;
    client_body_buffer_size    128k;

    client_body_temp_path      /var/nginx/client_body_temp;

    proxy_connect_timeout      90;
    proxy_send_timeout         90;
    proxy_read_timeout         90;
    proxy_send_lowat           12000;

    proxy_buffer_size          4k;
    proxy_buffers              4 32k;
    proxy_busy_buffers_size    64k;
    proxy_temp_file_write_size 64k;

    proxy_temp_path            /var/nginx/proxy_temp;

    charset  koi8-r;
    }

    error_page  404  /404.html;

    location /404.html {
    root  /spool/www;

    charset         on;
    source_charset  koi8-r;
    }

    location /old_stuff/ {
    rewrite   ^/old_stuff/(.*)$  /new_stuff/$1  permanent;
    }

    location /download/ {

    valid_referers  none  blocked  server_names  *.example.com;

    if ($invalid_referer) {
    #rewrite   ^/   http://www.example.com/;
    return   403;
    }

    #rewrite_log  on;

    # rewrite /download/*/mp3/*.any_ext to /download/*/mp3/*.mp3
    rewrite ^/(download/.*)/mp3/(.*)\..*$
    /$1/mp3/$2.mp3                   break;

    root         /spool/www;
    #autoindex    on;
    access_log   /var/log/nginx-download.access_log  download;
    }

    location ~* ^.+\.(jpg|jpeg|gif)$ {
    root         /spool/www;
    access_log   off;
    expires      30d;
    }
    }
    }

负载均衡
一个简单的负载均衡的示例,把www.domain.com均衡到本机不同的端口,也可以改为均衡到不同的地址上。>

http {
    upstream myproject {
    server 127.0.0.1:8000 weight=3;
    server 127.0.0.1:8001;
    server 127.0.0.1:8002;
    server 127.0.0.1:8003;
    }

    server {
    listen 80;
    server_name www.domain.com;
    location / {
    proxy_pass http://myproject;
    }
    }
}
nginx防盗链
location ~* \.(gif|jpg|png|swf|flv)$ {
root html
valid_referers none blocked *.nginxcn.com;
if ($invalid_referer) {
rewrite ^/ www.nginx.cn
#return 404;
}
}
前面的root可以不要如果你在server{}中有设置可以不需要设定


nginx日志和监控
FROM; http://nginx.com/resources/admin-guide/logging-and-monitoring/
http://www.2cto.com/os/201411/353118.html
Logging and Monitoring
日志和监控
This section describes how to configure logging of errors and processed requests, as well as how to use the runtime monitoring service of NGINX and NGINX Plus.
本文学习,如何配置错误日志与处理请求,以及如何使用NGINX和NGINX+的实时监控服务。
In This Section 本章有
    Setting up the error log 搭建错误日志
    Setting up the access log 搭建访问日志
    Logging to syslog 记录到系统日志
    Live activity monitoring 实时活动监控
Setting Up the Error Log
搭建错误日志
NGINX writes information about encountered issues of different severity levels to the error log. The error_log directive sets up logging to a partifular file, stderr, or syslog and specifies the minimal severity level of messages to log. By default, the error log is located at logs/error.log (the absolute path depends on the operating system and installation), and messages from all severity levels above the one specified are logged.
Nginx把遇到的不同级别的问题信息写到错误日志。error_log 指令配置记录到特定的文件,stderr,或者syslog,配置写到日志的最低级别信息。默认地,错误日志位于logs/error.log(绝对路径取决于操作系统和安装方式),比指定级别更高级别的信息都将被记录。
The configuration below changes the minimal severity level of error messages to log from error to warn.
下面这个配置把记录到日志的错误信息的最低级别由 error 改为 warn。
error_log logs/error.log warn;
In this case messages of warn, error, crit, alert, and emerg levels will be logged.
这样warn, error, crit, alert, emger 级别的信息都会被记录。
The default setting of the error log works globally. To override it, the error_logdirective should be placed in the main context. The settings of the main context are always inherited by other levels. The error_log directive can be specified on other levels too, cancelling the effect inherited from the higher levels. In case of an error, the message will be written to only one error log. This log will be the closest to the level where the error has occurred. However, if several error_log directives are specified on the same level, the message will be written to to all logs specified.
默认的错误日志设置是全局的。要覆盖它,error_log 指令必须放在main环境中。man环境里的设置都会被其他层继承。error_log指令也可以在其他层里指定,以取消从更高层继承下来的。如果发生一个错误,信息只会被写到一个错误日志。这个日志将写到错误发生的最近的那一层。然而,如果在同一个层定义了多个error_log指令,信息会被写到所有指定的日志文件。
Note    Using several error log directives at the same level are supported in NGINX versions 1.5.2 and greater.
注意:同一层使用多个错误日志需要Nginx版本为1.5.2或更高。

Setting Up the Access Log
设置访问日志
To the access a log, NGINX writes information about client requests after the request is processed. By default, the access log is located at logs/access.log, and the information is written to the log in the predefined, combined format. To override the default setting, use the log_format directive to configure a format of logged messages, as well as the access_log directive to specify the location of the log and the format. The format is defined using variables.
Nginx处理请求后把关于客户端请求的信息写到访问日志。默认,访问日志位于 logs/access.log,写到日志的信息是预定义的、组合的格式。要覆盖默认的配置,使用log_format指令来配置一个记录信息的格式,同样使用access_log 指令到设置日志和格式和位置。格式定义使用变量。
The following examples define a format that extends the standard combined format with the value indicating the ratio of gzip compression of the response. The format is then applied to a virtual server that enables compression.
下面这个例子定义一个格式,这个格式在标准组合格式上进行扩展加入对响应进行gzip压缩的比率的值。该格式被应用于一个开启了压缩的虚拟服务器。
http {
    log_format compression '$remote_addr - $remote_user [$time_local] '
                           '"$request" $status $body_bytes_sent '
                           '"$http_referer" "$http_user_agent" "$gzip_ratio"';

    server {
        gzip on;
        access_log /spool/logs/nginx-access.log compression;
        ...
    }
}

Logging can be optimized by enabling the buffer for log messages and the cache of descriptors of frequently used log files whose names contain variables. To enable buffering use the buffer parameter of the access_log directive to specify the size of the buffer. The buffered messages are then written to the log file when the next log message does not fit into the buffer as well as in some other cases. To enable caching of log file descriptors, use the open_log_file_cache directive.
开启日志信息缓冲,被频繁使用且名字包含变量的文件的操作的缓存,能够优化日志记录。要开始缓冲,使用access_log指令的buffer参数来指定缓冲的大小。缓冲区里的信息在缓冲区不够写下一个信息时以及另外的一些情况下写入日志文件。要开启文件操作的缓存,使用open_log_file_cache指令。
Similar to the error_log directive, the access_log directive defined on a level overrides the settings from the previous levels. When processing of a request is completed, the message is written to the log that is configured on the current level, or inherited from the previous levels. If one level defines multiple access logs, the message is written to all of them.
与error_log指令相似, 定义了access_log指令的层将会把从上一层继承下来的设置覆盖。当一个请求的处理完毕,信息被写到由当前层定义或者从上层继承下来的日志文件中。如果一个层里定义了多个访问日志,信息会被写到所有日志中。
Enabling Conditional Logging
开启有条件的日志记录
Conditional logging allows excluding trivial or non-important log entries from the access log. In NGINX, conditional logging is enabled by the if parameter of the access_log directive.
根据条件的日志记录能不记录细枝末节和不重要的日志条目到访问日志中。在Nginx中,条件性日志记录使用access_log指令的 if 参数开启。
For example, it makes possible to exclude requests with HTTP status codes 2XX (Success) and 3XX (Redirection):
例如,可以把状态码以2和3开头的HTTP请求忽略不计:
map $status $loggable {
    ~^[23]  0;
    default 1;
}
access_log /path/to/access.log combined if=$loggable;

Logging to Syslog
记录到系统日志
Syslog is a standard for computer message logging and allows collecting log messages from different devices on a single syslog server. In NGINX, logging to syslog is configured with the syslog    prefix in error_log and access_log directives.
系统日志是一个计算机信息记录标准,能够记录来自不同设备的日志信息到一个单一的系统日志服务器。在Nginx中,记录到系统日志要在error_log 和 access_log指令中加前缀 syslog    来配置。
Syslog messages can be sent to a server= which can be a domain name, an IP address, or a UNIX-domain socket path. A domain name or IP address can be specified with a port, by default port 514 is used. A UNIX-domain socket path can be specified after the unix:prefix:
系统日志信息能被发送到一个server=,server=后面可以是一个域名,一个IP地址或者一个unix-domain套接字路径。域名或者ip地址能指定端口,默认端口为514,unix-domain套接字路径跟在前缀unix:后:
error_log server=unix:/var/log/nginx.sock debug;
access_log syslog:server=[2001:db8::1]:1234,facility=local7,tag=nginx,severity=info;

In the example, NGINX error log messages will be written to UNIX domain socket with the debug logging level, and the access log will be written to a syslog server with IPv6 address and port 1234.
本例中,Nginx错误日志消息以debug日志级别记录到 UNIX 域套接字,访问日志将被记录到一个IPv6地址商品为1234的系统日志服务器。
The facility= parameter specifies the type of program which is logging the message. The default value is local7. Other values may be    auth, authpriv, daemon, cron, ftp, lpr,kern, mail,news, syslog, user, uucp, local0 … local7.
参数facility=指定记录日志消息的程序类型。缺省值为local7,其他可用值有    auth, authpriv,daemon, cron, ftp, lpr, kern, mail,news, syslog, user, uucp, local0 … local7.
The tag= parameter will apply a custom tag to syslog messages, in our example the tag is nginx.
参数tag=在系统日志消息中应用一个自定义标签,上例中标签为nginx。
The severity= parameter sets the severity level of syslog messages for access log. Possible values in order of increasing severity are    debug, info, notice, warn, error(default), crit, alert, and emerg. In our example, the severity level error will also enable crit, alert, and emerg levels to be logged.
参数severity=设置访问日志的系统日志消息的严重级别。可使用的值按严重级别顺序递增为:debug, info, notice, warn, error (default), crit, alert, and emerg。我们的例子中,严重级别error将开启crit, alert, emerg 级别的记录。
Live Activity Monitoring
实时活动监控
NGINX Plus provides a real-time activity monitoring interface that shows key load and performance metrics of your upstream servers as well as other data including:
Nginx + 提供一个实时活动监控界面,展示键的负载和上游服务器的性能指标,以及其他数据包括:
o    NIGNX basic version, uptime and identification information;
o    Nginx基础版本,运行时间和认证信息;
o    total and current numbers of connections and requests;
o    连接和请求的当前数目以及总数目;
o    request and response counts for each status_zone;
o    每个status_zone的请求和响应数;
o    request and response counts per server in each dynamically configured groups of servers, plus health-check and uptime statistics;
o    每个服务器动态配置组的请求和响应数,还有健康检测和正常运行时间统计;
o    statistics per server, including its current state and total values (total fails etc.)
o    统计每个服务器,包含当前状态和总体值(总体失败次数等)。
o    instrumentation for each named cache zone.
o    每个命名过的缓存空间的检测表。
The complete list of metrics is available here.
性能指标的完整列表点击此处。

The statistics can be viewed from the status.html page already included in each NGINX Plus package. The page polls status information and displays it in a simple table:
统计数据可以从status.html页面查看,该页面已包含在每个Nginx+的包里。页面统计状态信息并且展示在一个简单的表里:http://demo.nginx.com/status.html
And using a simple RESTful JSON interface, it’s easy to connect these stats to live dashboards and third-party monitoring tools.
还可以使用一个简单的 RESTful JSON 接口,可以通过第三方监控平台轻松连接这些状态做一个实时仪表盘。
Enabling Activity Monitoring
开启活动监控
To enable real-time activity monitoring and the JSON interface, you must specify the location that checks the exact match of the URI with /status and contains the status directive. To enable the status.html page, you must specify one more location that sets it:
要开启实时活动监控和 JSON 接口,必须在精确匹配 /status 的 location 里包含 status 指令。要启用status.html页面,你必须在至少一个location里设置它:
server {
    listen 127.0.0.1;
    root /usr/share/nginx/html;

    location /status {
        status;
    }

    location = /status.html {
    }
}

With the following configuration, the webpage status.html located at /usr/share/nginx/html can be requested by the URL http://127.0.0.1/status.html.
根据这个配置,网页status.html位于/usr/share/nginx/html能通过URL http://127.0.0.1/status.html 访问到。
Using RESTful JSON Interface
使用 RESTful JSON 接口
NGINX Plus stats can be easlily connected to third-party applications, such as performance dashboards. This can be done with the JSON interface.
Nginx+的统计能轻松连接到第三方应用,比如性能仪表盘。可以通过JSON接口实现。
If you request /status (or whichever URI matches the location group), then NGINX Plus will respond with a JSON document containing the current activity data.
如果你请求/status(或者任何一个能匹配这个location 组的URI),Nginx+将响应一个包含当前活动数据的JSON文档。
The status information of any element in the JSON document can be requested by a slash-separated URL:
JSON文档的每一个元素的状态信息都可以通过在请求后用斜线分隔的URL来请求:
http://127.0.0.1/status
http://127.0.0.1/status/nginx_version
http://127.0.0.1/status/caches/cache_backend
http://127.0.0.1/status/upstreams
http://127.0.0.1/status/upstreams/backend
http://127.0.0.1/status/upstreams/backend/1
http://127.0.0.1/status/upstreams/backend/1/weight
To learn more about NGINX Plus, please see the descriptions of our commercial subscriptions.

nginx访问日志,错误日志参数说明
application shang 2年前 (2012-10-16) 9310浏览 1评论
说明:
nginx日志主要有两种:访问日志、错误日志。其中访问日志记录客户端访问nginx的每一个请求,包含用户地域来源、跳转来源、使用终端、某个URL访问量等信息,访问日志格式可以自定义;错误日志则记录客户端访问nginx出错时的日志,格式不支持自定义,通过错误日志,你可以得到系统某个服务或server的性能瓶颈等。两种日志都可以选择性关闭。
 
访问日志[Access.log]
log_format  main  ‘$remote_addr $remote_user [$time_local] “$request” $http_host ‘
‘$status $upstream_status $body_bytes_sent “$http_referer” ‘
‘”$http_user_agent” $ssl_protocol $ssl_cipher $upstream_addr ‘
‘$request_time $upstream_response_time’;
变量名称    变量描述    举例说明
$remote_addr    客户端地址    113.140.15.90
$remote_user    客户端用户名称    -
$time_local    访问时间和时区    18/Jul/2012:17:00:01 +0800
$request    请求的URI和HTTP协议    “GET /pa/img/home/logo-alipay-t.png HTTP/1.1″
$http_host    请求地址,即浏览器中你输入的地址(IP或域名)    img.alipay.com
10.253.70.103
$status    HTTP请求状态    200
$upstream_status    upstream状态    200
$body_bytes_sent    发送给客户端文件内容大小    547
$http_referer    跳转来源     “https://cashier.alipay.com…/”
$http_user_agent    用户终端代理    “Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; SV1; GTB7.0; .NET4.0C;
$ssl_protocol    SSL协议版本    TLSv1
$ssl_cipher    交换数据中的算法    RC4-SHA
$upstream_addr    后台upstream的地址,即真正提供服务的主机地址    10.228.35.247:80
$request_time    整个请求的总时间    0.205
$upstream_response_time    请求过程中,upstream响应时间    0.002
 
线上实例:
116.9.137.90 – [02/Aug/2012:14:47:12 +0800] “GET /images/XX/20100324752729.png HTTP/1.1″img.alipay.com 200 200 2038 https://cashier.alipay.com/XX/PaymentResult.htm?payNo=XX&outBizNo=2012XX “Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; Tablet PC 2.0; 360SE)” TLSv1 AES128-SHA 10.228.21.237:80 0.198 0.001
 
线下测试($http_referer):
10.14.21.197 – - [14/Aug/2012:17:28:22 +0800] “GET /spanner/watch/v1?–db=ztg-1&–mode=compare&–index=status&–option=&–cluster=whole&-F=2012%2F8%2F12-00%3A00%3A00&-T=%2B2880&-i=1&-n=0&_=1344936501292 HTTP/1.1″ 200 94193 “http://spanner.alipay.net/optionFrame/history.html” “Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.60 Safari/537.1″

备注:$http_referer和重定向有关。
 
错误日志[Error.log]
错误信息    错误说明
“upstream prematurely(过早的) closed connection”    请求uri的时候出现的异常,是由于upstream还未返回应答给用户时用户断掉连接造成的,对系统没有影响,可以忽略
“recv() failed (104    Connection reset by peer)”    (1)服务器的并发连接数超过了其承载量,服务器会将其中一些连接Down掉; (2)客户关掉了浏览器,而服务器还在给客户端发送数据; (3)浏览器端按了Stop
“(111    Connection refused) while connecting to upstream”    用户在连接时,若遇到后端upstream挂掉或者不通,会收到该错误
“(111    Connection refused) while reading response header from upstream”    用户在连接成功后读取数据时,若遇到后端upstream挂掉或者不通,会收到该错误
“(111    Connection refused) while sending request to upstream”    Nginx和upstream连接成功后发送数据时,若遇到后端upstream挂掉或者不通,会收到该错误
“(110    Connection timed out) while connecting to upstream”    nginx连接后面的upstream时超时
“(110    Connection timed out) while reading upstream”    nginx读取来自upstream的响应时超时
 
“(110    Connection timed out) while reading response header from upstream”    nginx读取来自upstream的响应头时超时
“(110    Connection timed out) while reading upstream”    nginx读取来自upstream的响应时超时
“(104    Connection reset by peer) while connecting to upstream”    upstream发送了RST,将连接重置
“upstream sent invalid header while reading response header from upstream”    upstream发送的响应头无效
“upstream sent no valid HTTP/1.0 header while reading response header from upstream”    upstream发送的响应头无效
“client intended to send too large body”    用于设置允许接受的客户端请求内容的最大值,默认值是1M,client发送的body超过了设置值
“reopening logs”    用户发送kill  -USR1命令
“gracefully shutting down”,    用户发送kill  -WINCH命令
“no servers are inside upstream”    upstream下未配置server
“no live upstreams while connecting to upstream”    upstream下的server全都挂了
“SSL_do_handshake() failed”    SSL握手失败
“SSL_write() failed (SSL:) while sending to client”    
“(13    Permission denied) while reading upstream”    
“(98    Address already in use) while connecting to upstream”    
“(99    Cannot assign requested address) while connecting to upstream”    
“ngx_slab_alloc() failed    no memory in SSL session shared cache”    ssl_session_cache大小不够等原因造成
“could not add new SSL session to the session cache while SSL handshaking”    ssl_session_cache大小不够等原因造成
“send() failed (111    Connection refused)”    


高并发下的Nginx如何优化配置
我想你一定猜到了windows不在其中. Windows上的nginx确实没有什么理由让你值得使用. Windows有自己的一套处理事件polling. 所以nginx的作者选择了不支持. 因此默认的还是使用select() 这种不是很高效而且性能会下降很多的方式.(初次翻译不是很好希望多多指教)
第二个最大的限制, 也是大多数人会遇到的问题是和操作系统相关的. 打开一个shell窗口, 使用su命令切换到Nginx的运行用户, 运行命令`ulimit -a`. 这些值也会在Nginx在运行中对它进行限制. 在许多操作系统中, open files 的值是相当有限的, 在我使用的操作系统中, 它的值是 1024. 如果Nginx在运行中操作了这个限制他会记录error log(24    Too many open files) 接着返回一个操作给客户端.??当然Nginx可以处理的文件数可以更大你也可以针对操作系统做一些改动, 你可以放心的去增加这个值.
两种方式可以实现, 你可以通过ulimit设置os的    open files , 你还可以通过(nginx)配置?worker_rlimit_nofile?来申明你期望的值.

Nginx 限制
除了注意操作系统的限制, 现在我来深入到Nginx本身,看看一些指令和方法,我们可以用它来调整Nginx.
 Worker Processes
worker_process 是Nginx的主干, 一旦主进程绑定到指定的IP和端口,就会使用nginx指定的用户孵化出子进程, 之后他们会处理所有的工作. Workers 不是多线程的, 所以不能扩展它超过CPU的核数. 所以我们应该理解设置多个( 1)workers的原理, 通常一个CPU核对应一个worker. 过犹不及,2-4个workers会伤害CPU, 在CPU成为问题之前Nginx会遇到其他的瓶颈.而通常你只是看到了空闲的进程.(这段翻的太烂了希望大家多多改进)
当你正在处理下面这种情况, 你有很多的阻塞(blocking)磁盘IO,这是你可以适当增加worker_process的值. 你需要针您的配置进行测试,检查静态文件的等待时间(waiting time), 如果值比较大,可以适当的增加worker_process.(这段翻译完有想哭的感觉)
Worker Connections
worker_connections 是个稍稍有点怪的概念. 我不是很了解这个指令的目的, 但是它有效的限制了在同一时间内每个worker可以维护的连接数. 如果我没猜错的话, 这个配置是为了确保在keep-alive配置不正确的情况下, 当你使用的端口将要耗尽之时,增加连接数.(这个翻译的好难不知道是否正确因为作者也是forced to guess 我也只能被逼去猜了望指正)
默认的值是1024. 我们假设一般情况下打开2个连接来通过管道获取网站资源,也就是最多可以同时处理512个用户的请求.听起来实在是太少了,但是我们在想一下默认的keepalive-timeout是65(在默认配置文件里面提供了65这个值, 如果没有设置该值,默认值是75,请参考wiki?keepalive_timeout),也就是说我们实际上每秒只能处理8个连接. 显然这个值高于许多人期望的(我没觉得高呵呵),
To using The pack procrastinated and manageable ed medications review I. Skin canada pharmacy online the    did This. Trying viagra Very loved like with. Eyelashes viagra online You with. Hair bit, moisture generic online pharmacy expensive don't the The. Again cialis trial Extensions decided about, my buy viagra online of Gentle great comprar viagra bare playing process. Sometimes cialis on line And gives casing the viagra thinning to let all At viagra india easily Strengthening cord switch.
尤其是考虑到我们通常会设置2-4个workers. 但是对于流量较大的网站 使用keep-alive是值得的.(翻译完了又想哭了)
此外,我们还必须考虑反向代理, 这将打开一个额外的连接到后台,但是,自Nginx的不支持持久连接到后台,这不是太大的问题,除非你有长时间运行的后台进程.
所有关于worker连接的配置应该是相当清楚的,如果你流量增加了,你要相应的增加worker连接的数量。 2048对于大多数人来说应该是满足了,但老实说,如果你的流量增长了,那么对于workers的数量值应该是多少应该是很清楚的.
CPU 优先级
设置CPU的优先级,基本上意味着你告诉每个程序使用的CPU核心,而他们将只使用这个CPU核心。关于这一条,我不想说很多,但你要知道,如果你准备这样做,则必须非常小心。 要知道,你操作系统的 CPU 调度器处理负载均衡的能力要远远超过你。当然,如果你认为你的 CPU 负载均衡有问题,在调度层面上优化它,可能的话找一个替代的调度器。除非你知道你在做什么,否则不要碰这个。
Keep Alive
keep_alive 是 HTTP的一个特性, 它允许客户端维护与服务器已经创建的连接进行一批请求的处理直到指定的超时时间到达. 这个实际上不会在很大程度上改变我们的Nginxserver的性能, 因为Nginx能够很好的处理空闲的连接. Nginx的作者声称10,000个空闲的连接智慧使用2.5兆内存(unbelievable), 我个人的使用来说这个值也是靠谱的.
我在这篇性能文章里面提到这个原因非常简单. 对于最终用户来说keep alive对加载时间有着巨大的影响. 这是最重要的指标之一也是我们不断优化的原因.如果你的网站对用户来说感觉加载起来很快,他们就会很开心. Amazon和一些其他的大型在线零售商做过许多类似的研究表明, 网站的加载时间和网站订单的完成有着直接的关系.
为什么keep alive有着如此巨大的影响, 应该是显而易见的, 那就是你避免为所有的HTTP请求创建各自的连接, 这是非常低效的. 也许你不需要把keepalive-timeout设置为65, 但是10-20应该是比较通用的选择,正如上面一段所说, Nginx会很好的处理这方面.
tcp_nodelay 和 tcp_nopush
这两个指令也许是最难理解的nginx配置, 他们对于nginx的影响在网络的较低层. 你可以简单的认为这些指令决定了操作系统如何处理网络缓存和他们何时将这些缓存输出到最终用户(客户端). 我只能建议大家如果你之前不了解这些概念你最好不要动它. 他们不会显著的改善或者改变性能, 所以最好使用他们的默认值.
硬件限制
因为我们要处理nginx带来的所有可能的限制, 所以我们现在需要弄清楚如何有效的利用我们的服务器.为了做到这点我们需要看一下硬件层面的东西,由于大部分服务器瓶颈都会发生在这里.
一般服务器主要还有3个方面的瓶颈. CPU,内存和IO. Nginx在CPU的利用方面是非常高效的, 所以我会坦白的告诉你这不会成为瓶颈. 同样nginx在使用内存方面也是很高效的,这也不会成为瓶颈. 现在只剩下IO这个服务器瓶颈的罪魁祸首了.(搞得像找罪犯一样)
如果你经常使用服务器,那么你可能经历过这样认识。硬盘驱动器是真的,真的很慢。从硬盘驱动器读取可能是对服务器最昂贵的操作. 所以自然得出的结论是,为了避免IO瓶颈, 我们需要大量的减少nginx对硬盘驱动器的读写.
要做到这一点,我们可以通过修改Nginx的行为,以减少磁盘写操作,以及确保对nginx的内存限制,允许它避免磁盘访问。
Access Logs
默认情况下,Nginx的每个请求都会记录在磁盘上的日志文件中,你可以使用这个方法进行统计,安全问题检查等, 带着这会在一定程度上带来IO使用成本. 如果你不打算用这些访问日志来做一些检查或其他用途, 你可以直接关闭它以避免对磁盘写操作, 但是如果你需要访问日志,你可以考虑保存日志到内存中.这将会比直接写到磁盘上快很多,并且明显减少IO的使用.
如果你只打算使用访问日志进行统计,你可以考虑使用其他的比如google analytics来取代(ga和access log还是有区别的 不能简单的取代哦),或者你只记录访问请求的部分信息而不是全部.
Error Logs
我内心小小的挣扎了一把,我是否要在这里阐述这个error log 指令呢,因为也许你根本不希望关闭error log, 特别是考虑到实际应用中错误日志的量会很少. 但是考虑到这里指令有一个小小的地方需要引起大家注意, 错误日志的等级参数你是可以指定的, 如果你指定的太低了他会记录404错误甚至是debug信息. 在实际的应用中可以将它设置为warn级别,将会是绰绰有余的并且能降低IO.
Open File Cache
从文件系统中读取文件由2部分组成,打开和关闭文件. 考虑到这是一个有阻塞的操作,因此不要忽略这部分. 因此, 对于我们来说缓存打开文件的描述符是非常好的,这就是open_file_cache指令的由来. 链接的wiki地址里对于使用和配置它有着非常好的说明, 所以我建议你去拜读一下.
Buffers
配置Nginx缓存的大小是一个非常重要的事情. 如果缓存大小设置的太小, Nginx将不得不把上游(用英文upsteams会更好)的相应结果存放到临时的缓存文件里面,这将会同时增加IO的读写操作, 而且流量越大问题越多.
client_body_buffer_size指令用来指定处理客户端请求的缓冲区大小,?这个代表了访问请求的body. 这是用来处理POST的数据,也就是通过提交表单,文件上传等请求的数据. 如果你需要处理很多大的POST请求的,你必须确保缓存区要设置的足够大.
fastcgi_buffers?和?proxy_buffers?指令用来处理上流(upstream)的响应结果, 也就是PHP Apache等.它的概念其实和上面提到的差不多, 如果缓冲区不足够大数据将在返回给用户使用之前被保存到磁盘上. 注意Nginx将这个buffer数据同步的传输给客户端之前,有一个缓存上限, 保存到磁盘也同样受限. 这个上线是通过fastcgi_max_temp_file_size和proxy_max_temp_file_size来设置的. 另外对于代理的连接你也可以通过把proxy_buffering设置成off来彻底的关闭缓存.(通常这不是一个好办法).
彻底移除磁盘IO
最好的减少磁盘IO的方法无疑是不使用磁盘, 如果你的的应用只有少量的数据传输,你可以将数据都放入内存,这样就可以彻底不用考虑磁盘IO的阻塞了. 当然默认情况下你的操作系统也会缓存频繁访问的磁盘扇区, 所以内存越大磁盘的IO就会用到的越少. 这就意味着你可以通过增加内存来解决IO的瓶颈. 数据量越多,需要的内存越大.
网络IO
为了好玩,我们假设你有了足够大的内存来缓存你的所有数据. 这意味着理论上你的IO读速度达到了3-6gbps. 但是你没有那么快的网络通道. 不幸的是,我们可以优化的网络IO是有限的,我们要通过网络传输数据,所以还将受制于网络IO. 唯一真正有效的方法是尽量减少数据量或压缩。
幸运的是Nginx提供了gzip模块, 它可以使我们在将数据传输给客户端之前压缩它, 这将大大减少数据的大小. 一般来说 gzip_comp_level的值不会在性能方面有多大的差别,设为为4-5即可. 一味的增加它是没有意义的只是浪费的CPU的周期.
你也可以通过一些javascript和css缩小工具来减少传输文件大小. 但这些不是和Nginx很相关所以我相信你通过google可以获取更多的相关信息.

 

转载于:https://my.oschina.net/kenzheng/blog/1093921

你可能感兴趣的:(php,运维,json)