标签 nginx 下的文章

nginx内置预定义变量

nginx的配置文件中可以使用的内置变量以美元符$开始,也有人叫全局变量。其中,部分预定义的变量的值是可以改变的。
$arg_PARAMETER 这个变量值为:GET请求中变量名PARAMETER参数的值。

$args 这个变量等于GET请求中的参数。例如,foo=123&bar=blahblah;这个变量只可以被修改

$binary_remote_addr 二进制码形式的客户端地址。

$body_bytes_sent 传送页面的字节数

$content_length 请求头中的Content-length字段。

$content_type 请求头中的Content-Type字段。

$cookie_COOKIE cookie COOKIE的值。

$document_root 当前请求在root指令中指定的值。

$document_uri 与$uri相同。

$host 请求中的主机头(Host)字段,如果请求中的主机头不可用或者空,则为处理请求的server名称(处理请求的server的server_name指令的值)。值为小写,不包含端口。

$hostname 机器名使用 gethostname系统调用的值

$http_HEADER HTTP请求头中的内容,HEADER为HTTP请求中的内容转为小写,-变为_(破折号变为下划线),例如:$http_user_agent(Uaer-Agent的值), $http_referer...;

$sent_http_HEADER HTTP响应头中的内容,HEADER为HTTP响应中的内容转为小写,-变为_(破折号变为下划线),例如: $sent_http_cache_control, $sent_http_content_type...;

$is_args 如果$args设置,值为"?",否则为""。

$limit_rate 这个变量可以限制连接速率。

$nginx_version 当前运行的nginx版本号。

$query_string 与$args相同。

$remote_addr 客户端的IP地址。

$remote_port 客户端的端口。

$remote_user 已经经过Auth Basic Module验证的用户名。

$request_filename 当前连接请求的文件路径,由root或alias指令与URI请求生成。

$request_body 这个变量(0.7.58+)包含请求的主要信息。在使用proxy_pass或fastcgi_pass指令的location中比较有意义。

$request_body_file 客户端请求主体信息的临时文件名。

$request_completion 如果请求成功,设为"OK";如果请求未完成或者不是一系列请求中最后一部分则设为空。

$request_method 这个变量是客户端请求的动作,通常为GET或POST。
包括0.8.20及之前的版本中,这个变量总为main request中的动作,如果当前请求是一个子请求,并不使用这个当前请求的动作。

$request_uri 这个变量等于包含一些客户端请求参数的原始URI,它无法修改,请查看$uri更改或重写URI。

$scheme 所用的协议,比如http或者是https,比如rewrite ^(.+)$ $scheme://example.com$1 redirect;

$server_addr 服务器地址,在完成一次系统调用后可以确定这个值,如果要绕开系统调用,则必须在listen中指定地址并且使用bind参数。

$server_name 服务器名称。

$server_port 请求到达服务器的端口号。

$server_protocol 请求使用的协议,通常是HTTP/1.0或HTTP/1.1。

$uri 请求中的当前URI(不带请求参数,参数位于$args),不同于浏览器传递的$request_uri的值,它可以通过内部重定向,或者使用index指令进行修改。不包括协议和主机名,例如/foo/bar.html

转自 http://www.nginx.cn/273.html

nginx报502

nginx经常报这样的错误

2016/10/28 16:46:44 [error] 1919#0: *4340 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 127.0.0.1, server: www.xxxxx.com, request: "GET /test1.php HTTP/1.0", upstream: "fastcgi://127.0.0.1:9000", host: "www.xxxxx.com"

与此同时,php-fpm 也会报这样的错

Oct 28 16:46:44.654727 [WARNING] [pool www] child 2175 exited on signal 7 SIGBUS after 0.025646 seconds from start
Oct 28 16:46:44.655233 [NOTICE] [pool www] child 2178 started

百度之后,看到一边文章

原因是在php包含了一个文件之后,这个文件又发生了修改,于是发生了错误
重现错误可以使用如下代码,使用ab测试,就会报这样的错误

<?php

file_put_contents(__DIR__ . '/test.tpl', 'AAA<?php $string = "'. str_repeat('A', mt_rand(1, 256 * 1024)) .'"; ?>BBB' . "\r\n", LOCK_EX);

require_once __DIR__ . '/test.tpl';

echo "111";

?>

处理方法:
1、减少修改被包含的文件,模版解析之后的模版缓存文件

nginx和php-fpm环境记录php错误日志

转载自 http://www.jb51.net/article/49645.htm
nginx与apache不一样,在apache中可以直接指定php的错误日志,那样在php执行中的错误信息就直接输入到php的错误日志中,可以方便查询。
在nginx中事情就变成了这样:nginx只对页面的访问做access记录日志。不会有php的error log 信息。或者记录如下的很模糊的错误信息

2016/10/18 15:12:53 [error] 3232#0: *4688 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 121.121.121.121, server: dz.snsnb.com, request: "GET /admin.php?m=content&c=create_html&a=public_index&pc_hash=46yC97 HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "xxx.xxx.xxx", referrer: "http://xxx.xxx.xxx/admin.php?m=admin"

nginx把对php的请求发给php-fpm fastcgi进程来处理,默认的php-fpm只会输出php-fpm的错误信息,在php-fpm的errors log里也看不到php的errorlog。
原因是php-fpm的配置文件php-fpm.conf中默认是关闭worker进程的错误输出,直接把他们重定向到/dev/null,所以我们在nginx的error log 和php-fpm的errorlog都看不到php的错误日志。
所以我们要进行如下的设置就能查看到nginx下php-fpm不记录php错误日志的方法:

1,修改php-fpm.conf中的配置,如果没有请增加:(这一步做完,php的错误记录就会记录在php-fpm的日志中)

[global]
; Note: the default prefix is /usr/local/php/var
error_log = log/php_error_log
[www]
catch_workers_output = yes

2.修改php.ini中配置,没有则增加:(这一步无效,可能是与我的环境有关,不纠结了,第二步就已经可以看错误日志了)

log_errors = On
error_log = "/usr/local/php/var/log/error_log"
error_reporting=E_ALL&~E_NOTICE

3.重启php-fpm

当PHP执行错误时就能看到错误日志在”/usr/local/lnmp/php/var/log/php_error_log”中了
如果出现:

[root@localhost etc]# service php-fpm restart
Gracefully shutting down php-fpm . done
Starting php-fpm [17-Apr-2014 18:40:52] ERROR: [/usr/local/php/etc/php-fpm.conf:5] unknown entry 'catch_workers_
[17-Apr-2014 18:40:52] ERROR: failed to load configuration file '/usr/local/php/etc/php-fpm.conf'
[17-Apr-2014 18:40:52] ERROR: FPM initialization failed
 failed

那请在第一步的时候,认真将配置写入相对应的组中,不然就出现上面的:

ERROR: [/usr/local/php/etc/php-fpm.conf:5] unknown entry ‘catch_workers_output'

编译安装nginx,php

安装nginx

安装pcre

为了支持rewrite功能,我们需要安装pcre

yum install -y pcre* //如过你已经装了,请跳过这一步

需要ssl的支持,如果不需要ssl支持,请跳过这一步

yum install -y openssl*

编译安装

./configure --prefix=/usr/local/nginx-1.8.1 \
--with-http_spdy_module \
--with-http_stub_status_module \
--with-pcre

--with-http_stub_status_module:支持nginx状态查询
--with-http_spdy_module:支持google的spdy,想了解请百度spdy,这个必须有ssl的支持
--with-pcre:为了支持rewrite重写功能,必须制定pcre

报错

checking for OS
 + Linux 2.6.32-642.4.2.el6.x86_64 x86_64
checking for C compiler ... not found

./configure: error: C compiler cc is not found

安装所需的软件

yum -y install gcc gcc-c++

再 configure

报错

./configure: error: the HTTP gzip module requires the zlib library.
You can either disable the module by using --without-http_gzip_module
option, or install the zlib library into the system, or build the zlib library
statically from the source with nginx by using --with-zlib=&lt;path&gt; option.

安装所需软件

yum install -y zlib-devel

再 configure

Configuration summary
  + using system PCRE library
  + OpenSSL library is not used
  + using builtin md5 code
  + sha1 library is not found
  + using system zlib library

  nginx path prefix: "/usr/local/nginx-1.8.1"
  nginx binary file: "/usr/local/nginx-1.8.1/sbin/nginx"
  nginx configuration prefix: "/usr/local/nginx-1.8.1/conf"
  nginx configuration file: "/usr/local/nginx-1.8.1/conf/nginx.conf"
  nginx pid file: "/usr/local/nginx-1.8.1/logs/nginx.pid"
  nginx error log file: "/usr/local/nginx-1.8.1/logs/error.log"
  nginx http access log file: "/usr/local/nginx-1.8.1/logs/access.log"
  nginx http client request body temporary files: "client_body_temp"
  nginx http proxy temporary files: "proxy_temp"
  nginx http fastcgi temporary files: "fastcgi_temp"
  nginx http uwsgi temporary files: "uwsgi_temp"
  nginx http scgi temporary files: "scgi_temp"

安装

make //确定你的服务器有安装make,如果没有安装请执行yum install make
make install

添加启动脚本

这个网页可以 https://www.nginx.com/resources/wiki/start/topics/examples/redhatnginxinit/ 下载启动脚本

#!/bin/sh
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig:   - 85 15
# description:  NGINX is an HTTP(S) server, HTTP(S) reverse \
#               proxy and IMAP/POP3 proxy server
# processname: nginx
# config:      /etc/nginx/nginx.conf
# config:      /etc/sysconfig/nginx
# pidfile:     /var/run/nginx.pid

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0

nginx="/usr/sbin/nginx"
prog=$(basename $nginx)

NGINX_CONF_FILE="/etc/nginx/nginx.conf"

[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx

lockfile=/var/lock/subsys/nginx

make_dirs() {
   # make required directories
   user=`$nginx -V 2>&1 | grep "configure arguments:.*--user=" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
   if [ -n "$user" ]; then
      if [ -z "`grep $user /etc/passwd`" ]; then
         useradd -M -s /bin/nologin $user
      fi
      options=`$nginx -V 2>&1 | grep 'configure arguments:'`
      for opt in $options; do
          if [ `echo $opt | grep '.*-temp-path'` ]; then
              value=`echo $opt | cut -d "=" -f 2`
              if [ ! -d "$value" ]; then
                  # echo "creating" $value
                  mkdir -p $value && chown -R $user $value
              fi
          fi
       done
    fi
}

start() {
    [ -x $nginx ] || exit 5
    [ -f $NGINX_CONF_FILE ] || exit 6
    make_dirs
    echo -n $"Starting $prog: "
    daemon $nginx -c $NGINX_CONF_FILE
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}

stop() {
    echo -n $"Stopping $prog: "
    killproc $prog -QUIT
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}

restart() {
    configtest || return $?
    stop
    sleep 1
    start
}

reload() {
    configtest || return $?
    echo -n $"Reloading $prog: "
    killproc $nginx -HUP
    RETVAL=$?
    echo
}

force_reload() {
    restart
}

configtest() {
  $nginx -t -c $NGINX_CONF_FILE
}

rh_status() {
    status $prog
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}

case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart|configtest)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
            ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
        exit 2
esac

修改下面脚本中两项为实际的路径

#nginx="/usr/sbin/nginx"
nginx="/usr/local/nginx-1.8.1/sbin/nginx"
#NGINX_CONF_FILE="/etc/nginx/nginx.conf"
NGINX_CONF_FILE="/usr/local/nginx-1.8.1/conf/nginx.conf"

把文件写入到 /etc/init.d/nginx

给权限,开启服务器

chmod +x /etc/init.d/nginx
service nginx start

php 编译安装,版本 php-7.0.11

取官方下载程序包

安装依赖包

yum install gcc make gd-devel libjpeg-devel libpng-devel libxml2-devel bzip2-devel libcurl-devel -y

configure: error: Please reinstall the libzip distribution

7.3需要安装高版本的libzip

# 先安装高版本的cmake,不然无法安装libzip
wget https://gitlab.kitware.com/cmake/cmake/-/archive/v3.0.2/cmake-v3.0.2.tar.gz
tar -zxvf cmake-v3.0.2.tar.gz 
cd cmake-v3.0.2
./bootstrap 
gmake && gmake install

# 安装libzip
先删除老的版本
yum remove libzip

wget https://nih.at/libzip/libzip-1.5.1.tar.gz
tar -zxvf libzip-1.5.1.tar.gz
cd libzip-1.5.1
mkdir build
cd build
cmake ..
make
make test
make install

编译安装(64位系统需要加上最后一个 --with-libdir=lib64)

./configure --prefix=/usr/local/php-7.0.11 \
--with-config-file-path=/usr/local/php-7.0.11/etc \
--with-bz2 \
--with-curl \
--enable-ftp \
--enable-sockets \
--disable-ipv6 \
--with-gd \
--with-jpeg-dir=/usr/local \
--with-png-dir=/usr/local \
--with-freetype-dir=/usr/local \
--enable-gd-native-ttf \
--with-iconv-dir=/usr/local \
--enable-mbstring \
--enable-calendar \
--with-gettext \
--with-libxml-dir=/usr/local \
--with-zlib \
--with-pdo-mysql=mysqlnd \
--with-mysqli=mysqlnd \
--with-mysql=mysqlnd \
--enable-dom \
--enable-xml \
--enable-fpm \
--with-libdir=lib64

安装

make 
make test 
make install

复制 php 配置文件

cp php.ini-production /usr/local/php-7.0.11/etc/php.ini

复制 php-fpm 配置文件

cp /usr/local/php-7.0.11/etc/php-fpm.d/www.conf.default /usr/local/php-7.0.11/etc/php-fpm.d/www.conf

加入 service 管理脚本,修改到实际的路径即可

vim /etc/init.d/php7.0.11-fpm
#!/bin/bash
#
# Startup script for the PHP-FPM server.
#
# chkconfig: 345 85 15
# description: PHP is an HTML-embedded scripting language
# processname: php-7.0.11-fpm
# config: /usr/local/php/etc/php.ini
# config: /usr/local/php-7.0.11/etc/php.ini

# Source function library.
. /etc/rc.d/init.d/functions
# php 编译安装的目录
PHP_DIRECTORY=php-7.0.11
PHP_PATH=/usr/local/
DESC="php7.0.11-fpm daemon"
NAME=php-fpm
# php-fpm路径
DAEMON=$PHP_PATH/$PHP_DIRECTORY/sbin/$NAME
# 配置文件路径
CONFIGFILE=$PHP_PATH$PHP_DIRECTORY/etc/php-fpm.d/www.conf
# PID文件路径(在php-fpm.conf设置)
PIDFILE=$PHP_PATH/$PHP_DIRECTORY/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$PHP_DIRECORY

# Gracefully exit if the package has been removed.
test -x $DAEMON || exit 0

rh_start() {
  $DAEMON -y $CONFIGFILE || echo -n " already running"
}
rh_stop() {
  kill -QUIT `cat $PIDFILE` || echo -n " not running"
}

rh_reload() {
  kill -HUP `cat $PIDFILE` || echo -n " can't reload"
}

case "$1" in
  start)
        echo -n "Starting $DESC: $NAME"
        rh_start
        echo "."
        ;;
  stop)
        echo -n "Stopping $DESC: $NAME"
        rh_stop
        echo "."
        ;;
  reload)
        echo -n "Reloading $DESC configuration..."
        rh_reload
        echo "reloaded."
  ;;
  restart)
        echo -n "Restarting $DESC: $NAME"
        rh_stop
        sleep 1
        rh_start
        echo "."
        ;;
  *)
         echo "Usage: $SCRIPTNAME {start|stop|restart|reload}" &gt;&amp;2
         exit 3
        ;;
esac
exit 0

给执行权限
chmod +x php-7.0.11-fpm

设置 php-fpm pid 文件
在 php-fpm 配置文件的 [global] 部分加入 pid 设置项

vim /usr/local/php-7.0.11/etc/php-fpm.d/www.conf
#添加
[global]
pid = run/php-fpm.pid

nginx 配置

server {
        server_name www.jintest1.com;
        root /www/www.jintest1.com;
        index index.html index.php;
        location ~ .*\.(php)?$
        {
                expires -1s;
                try_files $uri =404;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                include fastcgi_params;
                fastcgi_param PATH_INFO $fastcgi_path_info;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_pass 127.0.0.1:9000;

        }
}

ok

nginx配置文件解析

user nginx nginx

Nginx用户及组:用户 组。window下不指定

worker_processes 8;

工作进程:数目。根据硬件调整,通常等于CPU数量或者2倍于CPU。

error_log logs/error.log; error_log logs/error.log notice; error_log logs/error.log info;

错误日志:存放路径。

pid logs/nginx.pid;

pid(进程标识符):存放路径。

worker_rlimit_nofile 204800;

指定进程可以打开的最大描述符:数目。
这个指令是指当一个nginx进程打开的最多文件描述符数目,理论值应该是最多打开文件数(ulimit -n)与nginx进程数相除,但是nginx分配请求并不是那么均匀,所以最好与ulimit -n 的值保持一致。 现在在linux 2.6内核下开启文件打开数为65535,worker_rlimit_nofile就相应应该填写65535。 这是因为nginx调度时分配请求到进程并不是那么的均衡,所以假如填写10240,总并发量达到3-4万时就有进程可能超过10240了,这时会返回502错误。

events {
use epoll;

使用epoll的I/O 模型。linux建议epoll,FreeBSD建议采用kqueue,window下不指定。 补充说明: 与apache相类,nginx针对不同的操作系统,有不同的事件模型 A)标准事件模型
#Select、poll属于标准事件模型,如果当前系统不存在更有效的方法,nginx会选择select或poll B)高效事件模型
#Kqueue:使用于FreeBSD 4.1+, OpenBSD 2.9+, NetBSD 2.0 和 MacOS X.使用双处理器的MacOS X系统使用kqueue可能会造成内核崩溃。
#Epoll:使用于Linux内核2.6版本及以后的系统。
#/dev/poll:使用于Solaris 7 11/99+,HP/UX 11.22+ (eventport),IRIX 6.5.15+ 和 Tru64 UNIX 5.1A+。 Eventport:使用于Solaris 10。 为了防止出现内核崩溃的问题, 有必要安装安全补丁。

worker_connections 204800;

每个工作进程的最大连接数量。根据硬件调整,和前面工作进程配合起来用,尽量大,但是别把cpu跑到100%就行。每个进程允许的最多连接数,理论上每台nginx服务器的最大连接数为。worker_processes*worker_connections

keepalive_timeout 60; keepalive

超时时间。

client_header_buffer_size 4k;

客户端请求头部的缓冲区大小。这个可以根据你的系统分页大小来设置,一般一个请求头的大小不会超过1k,不过由于一般系统分页都要大于1k,所以这里设置为分页大小。 分页大小可以用命令getconf PAGESIZE 取得。 [root@web001 ~]# getconf PAGESIZE 4096
但也有client_header_buffer_size超过4k的情况,但是client_header_buffer_size该值必须设置为“系统分页大小”的整倍数。

open_file_cache max=65535 inactive=60s;

这个将为打开文件指定缓存,默认是没有启用的,max指定缓存数量,建议和打开文件数一致,inactive是指经过多长时间文件没被请求后删除缓存。

open_file_cache_valid 80s;

这个是指多长时间检查一次缓存的有效信息。

open_file_cache_min_uses 1;

open_file_cache指令中的inactive参数时间内文件的最少使用次数,如果超过这个数字,文件描述符一直是在缓存中打开的,如上例,如果有一个文件在inactive时间内一次没被使用,它将被移除。

}
###设定http服务器,利用它的反向代理功能提供负载均衡支持

http {
includemime.types;

设定mime类型,类型由mime.type文件定义

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"';
log_format log404 '\$status [\$time_local] \$remote_addr \$host\$request_uri \$sent_http_location';

日志格式设置。
\$remote_addr与\$http_x_forwarded_for用以记录客户端的ip地址;
\$remote_user:用来记录客户端用户名称;
\$time_local: 用来记录访问时间与时区;
\$request: 用来记录请求的url与http协议;
\$status: 用来记录请求状态;成功是200,
\$body_bytes_sent :记录发送给客户端文件主体内容大小;
\$http_referer:用来记录从那个页面链接访问过来的;
\$http_user_agent:记录客户浏览器的相关信息;
通常web服务器放在反向代理的后面,这样就不能获取到客户的IP地址了,通过\$remote_add拿到的IP地址是反向代理服务器的iP地址。反向代理服务器在转发请求的http头信息中,可以增加x_forwarded_for信息,用以记录原有客户端的IP地址和原来客户端的请求的服务器地址。

access_log logs/host.access.log main;
access_log logs/host.access.404.log log404;

用了log_format指令设置了日志格式之后,需要用access_log指令指定日志文件的存放路径;

server_names_hash_bucket_size 128;

保存服务器名字的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的提示,那么首要的是增大前一个参数的大小.

client_header_buffer_size 4k;

客户端请求头部的缓冲区大小。这个可以根据你的系统分页大小来设置,一般一个请求的头部大小不会超过1k,不过由于一般系统分页都要大于1k,所以这里设置为分页大小。分页大小可以用命令getconf PAGESIZE取得。

large_client_header_buffers 8 128k;

客户请求头缓冲大小。nginx默认会用client_header_buffer_size这个buffer来读取header值,如果 header过大,它会使用large_client_header_buffers来读取。
open_file_cache max=102400 inactive=20s; #这个指令指定缓存是否启用。 
#例: open_file_cache max=1000 inactive=20s;   
    #open_file_cache_valid 30s;   
    #open_file_cache_min_uses 2;   
    #open_file_cache_errors on; 
    语法:open_file_cache_errors on | off 默认值:open_file_cache_errors off 使用字段:http, server, location 这个指令指定是否在搜索一个文件是记录cache错误. open_file_cache_min_uses 
    语法:open_file_cache_min_uses number 默认值:open_file_cache_min_uses 1 使用字段:http, server, location 这个指令指定了在open_file_cache指令无效的参数中一定的时间范围内可以使用的最小文件数,如果使用更大的值,文件描述符在cache中总是打开状态. open_file_cache_valid 
    语法:open_file_cache_valid time 默认值:open_file_cache_valid 60 使用字段:http, server, location 这个指令指定了何时需要检查open_file_cache中缓存项目的有效信息.

client_max_body_size 300m;

设定通过nginx上传文件的大小

sendfile on;

sendfile指令指定 nginx 是否调用sendfile 函数(zero copy 方式)来输出文件,对于普通应用,必须设为on。如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络IO处理速度,降低系统uptime。

tcp_nopush on;

此选项允许或禁止使用socke的TCP_CORK的选项,此选项仅在使用sendfile的时候使用

proxy_connect_timeout 90;

后端服务器连接的超时时间_发起握手等候响应超时时间

proxy_read_timeout 180;

连接成功后

等候后端服务器响应时间

其实已经进入后端的排队之中等候处理(也可以说是后端服务器处理请求的时间)

proxy_send_timeout 180;

后端服务器数据回传时间_就是在规定时间之内后端服务器必须传完所有的数据

proxy_buffer_size 256k;

设置从被代理服务器读取的第一部分应答的缓冲区大小,通常情况下这部分应答中包含一个小的应答头,默认情况下这个值的大小为指令proxy_buffers中指定的一个缓冲区的大小,不过可以将其设置为更小

proxy_buffers 4 256k;

设置用于读取应答(来自被代理服务器)的缓冲区数目和大小,默认情况也为分页大小,根据操作系统的不同可能是4k或者8k

proxy_busy_buffers_size 256k;

proxy_temp_file_write_size 256k;

设置在写入proxy_temp_path时数据的大小,预防一个工作进程在传递文件时阻塞太长

proxy_temp_path /data0/proxy_temp_dir;

proxy_temp_path和proxy_cache_path指定的路径必须在同一分区

proxy_cache_path /data0/proxy_cache_dir levels=1:2 keys_zone=cache_one:200m inactive=1d max_size=30g;

设置内存缓存空间大小为200MB,1天没有被访问的内容自动清除,硬盘缓存空间大小为30GB。

keepalive_timeout 120;

keepalive超时时间。

tcp_nodelay on;

client_body_buffer_size 512k;

如果把它设置为比较大的数值,例如256k,那么,无论使用firefox还是IE浏览器,来提交任意小于256k的图片,都很正常。如果注释该指令,使用默认的client_body_buffer_size设置,也就是操作系统页面大小的两倍,8k或者16k,问题就出现了。
无论使用firefox4.0还是IE8.0,提交一个比较大,200k左右的图片,都返回500 Internal Server Error错误

proxy_intercept_errors on;

表示使nginx阻止HTTP应答代码为400或者更高的应答。

upstream bakend{ server 127.0.0.1:8027; server 127.0.0.1:8028; server 127.0.0.1:8029; hash \$request_uri; }
nginx的upstream目前支持4种方式的分配
1、轮询(默认)
每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除。
2、weight
指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。 例如:

    upstream bakend{ 
        server 192.168.0.14 weight=10; server 192.168.0.15 weight=10; 
    } 

2、ip_hash
每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题。 例如:

    upstream bakend { 
        ip_hash; 
        server 192.168.0.14:88; server 192.168.0.15:80; 
    } 

3、fair(第三方)
按后端服务器的响应时间来分配请求,响应时间短的优先分配。

    upstream backend { 
        server server1; server server2;
        fair; 
    } 

4、url_hash(第三方)
按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,后端服务器为缓存时比较有效。 例:在upstream中加入hash语句,server语句中不能写入weight等其他的参数,hash_method是使用的hash算法

    upstream backend { 
        server squid1:3128; server squid2:3128; hash $request_uri; hash_method crc32; 
    } 

tips:
upstream bakend{#定义负载均衡设备的Ip及设备状态}{
ip_hash;
server 127.0.0.1:9090 down;
server 127.0.0.1:8080 weight=2;
server 127.0.0.1:6060;
server 127.0.0.1:7070 backup;
}
在需要使用负载均衡的server中增加 proxy_pass http://bakend/; 每个设备的状态设置为:
1.down表示单前的server暂时不参与负载
2.weight为weight越大,负载的权重就越大。
3.max_fails:允许请求失败的次数默认为1.当超过最大次数时,返回proxy_next_upstream模块定义的错误
4.fail_timeout:max_fails次失败后,暂停的时间。
5.backup: 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。
nginx支持同时设置多组的负载均衡,用来给不用的server来使用。
client_body_in_file_only设置为On 可以讲client post过来的数据记录到文件中用来做debug
client_body_temp_path设置记录文件的目录 可以设置最多3层目录
location对URL进行匹配.可以进行重定向或者进行新的代理 负载均衡
###配置虚拟机

server { 
    listen 80; 
    #配置监听端口  

    server_name image.***.com; 
    #配置访问域名
    location ~* \.(mp3|exe)$ { 
    #对以“mp3或exe”结尾的地址进行负载均衡  
        proxy_pass http://img_relay$request_uri; 
        #设置被代理服务器的端口或套接字,以及URL  
        proxy_set_header Host $host; 
        proxy_set_header X-Real-IP $remote_addr; 
        #以上三行,目的是将代理服务器收到的用户的信息传到真实服务器上 
    }  
    location /face { 
        if ($http_user_agent ~* "xnp") { 
            rewrite ^(.*)$ http://211.151.188.190:8080/face.jpg redirect; 
        } 
        proxy_pass http://img_relay$request_uri; proxy_set_header Host $host; 
        proxy_set_header X-Real-IP $remote_addr; 
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        error_page 404 502 = @fetch; 
    } 
    location @fetch { 
        access_log /data/logs/face.log log404; 
        rewrite ^(.*)$ http://211.151.188.190:8080/face.jpg redirect; 
    } 
    location /image { 
        if ($http_user_agent ~* "xnp") { 
            rewrite ^(.*)$ http://211.151.188.190:8080/face.jpg redirect; 
        } 
        proxy_pass http://img_relay$request_uri; proxy_set_header Host $host; 
        proxy_set_header X-Real-IP $remote_addr; 
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
    } 
    location @fetch { 
        access_log /data/logs/image.log log404; 
        rewrite ^(.*)$ http://211.151.188.190:8080/face.jpg redirect; 
    } 
}

###其他举例

server { 
    listen 80; 
    server_name *.***.com *.***.cn; 
    location ~* \.(mp3|exe)$ { 
        proxy_pass http://img_relay$request_uri; proxy_set_header Host $host; 
        proxy_set_header X-Real-IP $remote_addr; 
    } 
    location / { 
    if ($http_user_agent ~* "xnp") { 
        rewrite ^(.*)$ http://i1.***img.com/help/noimg.gif redirect; 
    } 
        proxy_pass http://img_relay$request_uri; proxy_set_header Host $host; 
        proxy_set_header X-Real-IP $remote_addr; 
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
        #error_page 404 http://i1.***img.com/help/noimg.gif; 
        error_page 404 502 = @fetch; 
    } 
    location @fetch { 
        access_log /data/logs/baijiaqi.log log404; 
        rewrite ^(.*)$ http://i1.***img.com/help/noimg.gif redirect; 
    } 
}
server { 
    listen 80; 
    server_name *.***img.com;  
    location ~* \.(mp3|exe)$ { 
        proxy_pass http://img_relay$request_uri; 
        proxy_set_header Host $host; 
        proxy_set_header X-Real-IP $remote_addr; 
    } 
    location / { 
    if ($http_user_agent ~* "xnp") { 
        rewrite ^(.*)$ http://i1.***img.com/help/noimg.gif; 
    } 
        proxy_pass http://img_relay$request_uri; proxy_set_header Host $host; 
        proxy_set_header X-Real-IP $remote_addr; 
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
        error_page 404 = @fetch; 
    } 
    #access_log off; 
    location @fetch { 
    access_log /data/logs/baijiaqi.log log404; 
    } 
} 
server { 
    listen 8080; 
    server_namengx-ha.***img.com; 
    stub_status on; access_log off; 
} 
server { 
    listen 80; 
    server_name imgsrc1.***.net; root html; 
}
    server { 
        listen 80; 
        server_name ***.com w.***.com; 
        # access_log /usr/local/nginx/logs/access_log main; 
        location / { 
        } 
    } 
server { 
    listen 80; 
    server_name *******.com w.*******.com; 
    # access_log /usr/local/nginx/logs/access_log main; location / { 
    rewrite ^(.*)$ http://www.*******.com/; 
    } 
} 
server { listen 80; 
    server_name ******.com; 
    # access_log /usr/local/nginx/logs/access_log main; 
    location / { 
    } 
}
    location /NginxStatus { 
        access_log on; 
        auth_basic "NginxStatus"; 
        auth_basic_user_fileconf/htpasswd; 
    }
    #设定查看Nginx状态的地址 
    location ~ /\.ht { 
        deny all; 
    } 
    #禁止访问.htxxx文件 
}

###注释:变量

Ngx_http_core_module模块支持内置变量,他们的名字和apache的内置变量是一致的。 首先是说明客户请求title中的行,例如\$http_user_agent,\$http_cookie等等。 此外还有其它的一些变量
\$args此变量与请求行中的参数相等
\$content_length等于请求行的“Content_Length”的值。
\$content_type等同与请求头部的”Content_Type”的值 \$document_root等同于当前请求的root指令指定的值 \$document_uri与\$uri一样
\$host与请求头部中“Host”行指定的值或是request到达的server的名字(没有Host行)一样
\$limit_rate允许限制的连接速率
\$request_method等同于request的method,通常是“GET”或“POST”
\$remote_addr客户端ip
\$remote_port客户端port
\$remote_user等同于用户名,由ngx_http_auth_basic_module认证
\$request_filename当前请求的文件的路径名,由root或alias和URI request组合而成 \$request_body_file
\$request_uri含有参数的完整的初始URI \$query_string与\$args一样
\$sheeme http模式(http,https)尽在要求是评估例如
Rewrite ^(.+)\$ \$sheme://example.com\$; Redirect;
\$server_protocol等同于request的协议,使用“HTTP/或“HTTP/
\$server_addr request到达的server的ip,一般获得此变量的值的目的是进行系统调用。为了避免系统调用,有必要在listen指令中指明ip,并使用bind参数。 \$server_name请求到达的服务器名 \$server_port请求到达的服务器的端口号
\$uri等同于当前request中的URI,可不同于初始值,例如内部重定向时或使用index