nginx 详细用法

一、Nginx 安装及调试

需要的依赖包gcc  pcre  pcre-devel gd gd-devel openssl

1、Pcre 安装

./configure

make && make install

2. nginx 编译安装

/configure --user=www --group=www --prefix=/usr/local/nginx/ --with-http_stub_status_module

--with-openssl=/usr/local/openssl

make && make install

3、Nginx 配置文件测试:

# /usr/local/nginx/sbin/nginx -t //Debug 配置文件的关键命令需要重点撑握.

2008/12/16 09:08:35 [info] 28412#0: the configuration file /usr/local/nginx/conf/nginx.conf

syntax is ok

2008/12/16 09:08:35 [info] 28412#0: the configuration file /usr/local/nginx/conf/nginx.conf was

tested successfully

3、 Nginx 启动:

# /usr/local/nginx/sbin/nginx

4、 Nginx 配置文件修改重新加载:

# kill -HUP `cat /usr/local/nginx/logs/nginx.pid `

配置文件及说明

关于Nginx的一些优化(突破十万并发)

nginx指令中的优化(配置文件)

worker_processes 8;

nginx进程数,建议按照cpu数目来指定,一般为它的倍数。

worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;

为每个进程分配cpu,上例中将8个进程分配到8个cpu,当然可以写多个,或者将一个进程分配到多个cpu。

worker_rlimit_nofile 102400;

这个指令是指当一个nginx进程打开的最多文件描述符数目,理论值应该是最多打开文件数(ulimit -n)与nginx进程数相除,但是nginx分配请求并不是那么均匀,所以最好与ulimit -n的值保持一致。

use epoll;

使用epoll的I/O模型,这个不用说了吧。

worker_connections 102400;

每个进程允许的最多连接数,理论上每台nginx服务器的最大连接数为worker_processes*worker_connections。

keepalive_timeout 60;

keepalive超时时间。

client_header_buffer_size 4k;

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

open_file_cache max=102400 inactive=20s;

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

open_file_cache_valid 30s;

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

open_file_cache_min_uses 1;

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

内核参数的优化

net.ipv4.tcp_max_tw_buckets = 6000

timewait的数量,默认是180000。

net.ipv4.ip_local_port_range = 1024    65000

允许系统打开的端口范围。

net.ipv4.tcp_tw_recycle = 1

启用timewait快速回收。

net.ipv4.tcp_tw_reuse = 1

开启重用。允许将TIME-WAIT sockets重新用于新的TCP连接。

net.ipv4.tcp_syncookies = 1

开启SYN Cookies,当出现SYN等待队列溢出时,启用cookies来处理。

net.core.somaxconn = 262144

web应用中listen函数的backlog默认会给我们内核参数的net.core.somaxconn限制到128,而nginx定义的NGX_LISTEN_BACKLOG默认为511,所以有必要调整这个值。

net.core.netdev_max_backlog = 262144

每个网络接口接收数据包的速率比内核处理这些包的速率快时,允许送到队列的数据包的最大数目。

net.ipv4.tcp_max_orphans = 262144

系统中最多有多少个TCP套接字不被关联到任何一个用户文件句柄上。如果超过这个数字,孤儿连接将即刻被复位并打印出警告信息。这个限制仅仅是为了防止简单的DoS***,不能过分依靠它或者人为地减小这个值,更应该增加这个值(如果增加了内存之后)。

net.ipv4.tcp_max_syn_backlog = 262144

记录的那些尚未收到客户端确认信息的连接请求的最大值。对于有128M内存的系统而言,缺省值是1024,小内存的系统则是128。

net.ipv4.tcp_timestamps = 0

时间戳可以避免序列号的卷绕。一个1Gbps的链路肯定会遇到以前用过的序列号。时间戳能够让内核接受这种“异常”的数据包。这里需要将其关掉。

net.ipv4.tcp_synack_retries = 1

为了打开对端的连接,内核需要发送一个SYN并附带一个回应前面一个SYN的ACK。也就是所谓三次握手中的第二次握手。这个设置决定了内核放弃连接之前发送SYN+ACK包的数量。

net.ipv4.tcp_syn_retries = 1

在内核放弃建立连接之前发送SYN包的数量。

net.ipv4.tcp_fin_timeout = 1

如果套接字由本端要求关闭,这个参数决定了它保持在FIN-WAIT-2状态的时间。对端可以出错并永远不关闭连接,甚至意外当机。缺省值是60秒。2.2 内核的通常值是180秒,你可以按这个设置,但要记住的是,即使你的机器是一个轻载的WEB服务器,也有因为大量的死套接字而内存溢出的风险,FIN- WAIT-2的危险性比FIN-WAIT-1要小,因为它最多只能吃掉1.5K内存,但是它们的生存期长些。

net.ipv4.tcp_keepalive_time = 30

当keepalive起用的时候,TCP发送keepalive消息的频度。缺省是2小时。

一个完整的内核优化配置

net.ipv4.ip_forward = 0

net.ipv4.conf.default.rp_filter = 1

net.ipv4.conf.default.accept_source_route = 0

kernel.sysrq = 0

kernel.core_uses_pid = 1

net.ipv4.tcp_syncookies = 1

kernel.msgmnb = 65536

kernel.msgmax = 65536

kernel.shmmax = 68719476736

kernel.shmall = 4294967296

net.ipv4.tcp_max_tw_buckets = 6000

net.ipv4.tcp_sack = 1

net.ipv4.tcp_window_scaling = 1

net.ipv4.tcp_rmem = 4096        87380   4194304

net.ipv4.tcp_wmem = 4096        16384   4194304

net.core.wmem_default = 8388608

net.core.rmem_default = 8388608

net.core.rmem_max = 16777216

net.core.wmem_max = 16777216

net.core.netdev_max_backlog = 262144

net.core.somaxconn = 262144

net.ipv4.tcp_max_orphans = 3276800

net.ipv4.tcp_max_syn_backlog = 262144

net.ipv4.tcp_timestamps = 0

net.ipv4.tcp_synack_retries = 1

net.ipv4.tcp_syn_retries = 1

net.ipv4.tcp_tw_recycle = 1

net.ipv4.tcp_tw_reuse = 1

net.ipv4.tcp_mem = 94500000 915000000 927000000

net.ipv4.tcp_fin_timeout = 1

net.ipv4.tcp_keepalive_time = 30

net.ipv4.ip_local_port_range = 1024    65000

一个简单的nginx优化配置文件

user  www www;

worker_processes 8;

worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000;

error_log  /www/log/nginx_error.log  crit;

pid        /usr/local/nginx/nginx.pid;

worker_rlimit_nofile 204800;

events

{

 use epoll;

 worker_connections 204800;

}

http

{

 include       mime.types;

 default_type  application/octet-stream;

 charset  utf-8;

 server_names_hash_bucket_size 128;

 client_header_buffer_size 2k;

 large_client_header_buffers 4 4k;

 client_max_body_size 8m;

 sendfile on;

 tcp_nopush     on;

 keepalive_timeout 60;

 fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2

               keys_zone=TEST:10m

               inactive=5m;

 fastcgi_connect_timeout 300;

 fastcgi_send_timeout 300;

 fastcgi_read_timeout 300;

 fastcgi_buffer_size 16k;

 fastcgi_buffers 16 16k;

 fastcgi_busy_buffers_size 16k;

 fastcgi_temp_file_write_size 16k;

 fastcgi_cache TEST;

 fastcgi_cache_valid 200 302 1h;

 fastcgi_cache_valid 301 1d;

 fastcgi_cache_valid any 1m;

 fastcgi_cache_min_uses 1;

 fastcgi_cache_use_stale error timeout invalid_header http_500;

 open_file_cache max=204800 inactive=20s;

 open_file_cache_min_uses 1;

 open_file_cache_valid 30s;

 tcp_nodelay on;

 gzip on;

 gzip_min_length  1k;

 gzip_buffers     4 16k;

 gzip_http_version 1.0;

 gzip_comp_level 2;

 gzip_types       text/plain application/x-javascript text/css application/xml;

 gzip_vary on;



 server

 {

   listen       8080;

   server_name  ad.test.com;

   index index.php index.htm;

   root  /www/html/;


   location /status

   {

       stub_status on;

   }


   location ~ .*\.(php|php5)?$

   {

       fastcgi_pass 127.0.0.1:9000;

       fastcgi_index index.php;

       include fcgi.conf;

   }


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

   {

     expires      30d;

   }


   log_format  access  '$remote_addr - $remote_user [$time_local] "$request" '

             '$status $body_bytes_sent "$http_referer" '

             '"$http_user_agent" $http_x_forwarded_for';

   access_log  /www/log/access.log  access;

     }

}

关于FastCGI的几个指令

fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2 keys_zone=TEST:10m inactive=5m;

这个指令为FastCGI缓存指定一个路径,目录结构等级,关键字区域存储时间和非活动删除时间。

fastcgi_connect_timeout 300;

指定连接到后端FastCGI的超时时间。

fastcgi_send_timeout 300;

向FastCGI传送请求的超时时间,这个值是指已经完成两次握手后向FastCGI传送请求的超时时间。

fastcgi_read_timeout 300;

接收FastCGI应答的超时时间,这个值是指已经完成两次握手后接收FastCGI应答的超时时间。

fastcgi_buffer_size 16k;

指定读取FastCGI应答第一部分需要用多大的缓冲区,这里可以设置为fastcgi_buffers指令指定的缓冲区大小,上面的指令指定它将使用1个16k的缓冲区去读取应答的第一部分,即应答头,其实这个应答头一般情况下都很小(不会超过1k),但是你如果在fastcgi_buffers指令中指定了缓冲区的大小,那么它也会分配一个fastcgi_buffers指定的缓冲区大小去缓存。

fastcgi_buffers 16 16k;

指定本地需要用多少和多大的缓冲区来缓冲FastCGI的应答,如上所示,如果一个php脚本所产生的页面大小为256k,则会为其分配16个16k的缓冲区来缓存,如果大于256k,增大于256k的部分会缓存到fastcgi_temp指定的路径中,当然这对服务器负载来说是不明智的方案,因为内存中处理数据速度要快于硬盘,通常这个值的设置应该选择一个你的站点中的php脚本所产生的页面大小的中间值,比如你的站点大部分脚本所产生的页面大小为256k就可以把这个值设置为16 16k,或者4 64k 或者64 4k,但很显然,后两种并不是好的设置方法,因为如果产生的页面只有32k,如果用4 64k它会分配1个64k的缓冲区去缓存,而如果使用64 4k它会分配8个4k的缓冲区去缓存,而如果使用16 16k则它会分配2个16k去缓存页面,这样看起来似乎更加合理。

fastcgi_busy_buffers_size 32k;

这个指令我也不知道是做什么用,只知道默认值是fastcgi_buffers的两倍。

fastcgi_temp_file_write_size 32k;

在写入fastcgi_temp_path时将用多大的数据块,默认值是fastcgi_buffers的两倍。

fastcgi_cache TEST

开启FastCGI缓存并且为其制定一个名称。个人感觉开启缓存非常有用,可以有效降低CPU负载,并且防止502错误。但是这个缓存会引起很多问题,因为它缓存的是动态页面。具体使用还需根据自己的需求。

fastcgi_cache_valid 200 302 1h;

fastcgi_cache_valid 301 1d;

fastcgi_cache_valid any 1m;

为指定的应答代码指定缓存时间,如上例中将200,302应答缓存一小时,301应答缓存1天,其他为1分钟。

fastcgi_cache_min_uses 1;

缓存在fastcgi_cache_path指令inactive参数值时间内的最少使用次数,如上例,如果在5分钟内某文件1次也没有被使用,那么这个文件将被移除。

fastcgi_cache_use_stale error timeout invalid_header http_500;

不知道这个参数的作用,猜想应该是让nginx知道哪些类型的缓存是没用的。 以上为nginx中FastCGI相关参数,另外,FastCGI自身也有一些配置需要进行优化,如果你使用php-fpm来管理FastCGI,可以修改配置文件中的以下值:

<value name="max_children">60</value>

同时处理的并发请求数,即它将开启最多60个子线程来处理并发连接。

<value name="rlimit_files">102400</value>

最多打开文件数。

<value name="max_requests">204800</value>

每个进程在重置之前能够执行的最多请求数。


二、 Nginx Rewrite

1. Nginx Rewrite 基本标记(flags)

last - 基本上都用这个Flag。

※相当于Apache里的[L]标记,表示完成rewrite,不再匹配后面的规则

break - 中止Rewirte,不再继续匹配

redirect - 返回临时重定向的HTTP状态302

permanent - 返回永久重定向的HTTP状态301

※原有的url支持正则 重写的url不支持正则

2. 正则表达式匹配,其中:

~ 为区分大小写匹配

~* 为不区分大小写匹配

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

3. 文件及目录匹配,其中:

-f 和 !-f 用来判断是否存在文件

-d 和 !-d 用来判断是否存在目录

-e 和 !-e 用来判断是否存在文件或目录

-x 和 !-x 用来判断文件是否可执行

3. Nginx 的一些可用的全局变量,可用做条件判断:

$args

$content_length

$content_type

$document_root

$document_uri

$host

$http_user_agent

$http_cookie

$limit_rate

$request_body_file

$request_method

$remote_addr

$remote_port

$remote_user

$request_filename

$request_uri

$query_string

$scheme

$server_protocol

$server_addr

$server_name

$server_port

$uri

三、 Nginx Redirect

1、将所有linuxtone.org与netseek.linuxtone.org域名全部自跳转到http://www.linuxtone.org

server {

   listen 80;

   server_name linuxtone.org netseek.linuxtone.org;

   index index.html index.php;

   root /data/www/wwwroot;

   if ($host ~! "^www\.linxtone\.org$") {

       rewrite ^(.*) http://www.linuxtone.org$1 redirect;

   }

   .....................

}

2、Nginx  rewrite last && rewrite break 的区别

Rewrite( URL 重写)指令可以出现在 server{} 下,也可以出现在 location{} 下,它们之间是有区别的!

对于出现在 server{} 下的 rewrite 指令,它的执行会在 location 匹配之前;对于出现在 location{} 下的 rewrite 指令,它的执行当然是在 location 匹配之后,但是由于 rewrite 导致 HTTP 请求的 URI 发生了变化,所以 location{} 下的 rewrite 后的 URI 又需要重新匹配 location ,就好比一个新的 HTTP 请求一样(注意由 location{} 内的 rewrite 导致的这样的循环匹配最多不超过 10 次,否则 nginx 会报 500 错误)。总的来说,如果 server{} 和 location{} 下都有 rewrite ,依然是先执行 server{} ,然后进行 location 匹配,如果被匹配的 location{} 之内还有 rewrite 指令,那么继续执行 rewrite ,同时因为 location{} 内的 rewrite 改变了 URI ,那么重写后的结果 URI 需要当做一个新的请求,重新匹配 location (也包括重新执行 server{} 下的 rewrite )

1、修改nginx 配置文件,测试用代码如下:

server {

       listen       9090;

       server_name  nginxtest.com;

       access_log  logs/nginxtest.com.log  main;

       error_log  logs/testerror.com.log   info;

       rewrite_log on;

       root   /data/program/nginx/html;

       location /aaa.html{

       rewrite "^/aaa\.html$" /bbb.html;

       rewrite "^/bbb\.html$" /ddd.html;

       }

       location /bbb.html{

       rewrite "^/bbb\.html$" /ccc.html;

       }

  }

2、在html 目录下新建aaa.html bbb.html ccc.html ddd.html

注意事项:

a、打开rewrite 模块输出日志 rewrite_log on;

b、错误日志的输出级别为info

c、定义两个location 如配置

3、【测试一】

curl http://nginxtest.com:9090/aaa.html

没有last和break 标记时:请求aaa.html,输出日志:

091900221.jpg


http请求 GET /aaa.html -->重写 /bbb.html -->重写/ddd.html,重写执行完了依次执行rewrite,事实上还有一步在日志中没有体现当执行重写到/ddd.html 后需要再次匹配location 如果有/ddd.html的location语句那么需要执行,没有故而输出了/ddd.html

【测试二】使用last标记时:请求aaa.html

curl http://nginxtest.com:9090/aaa.html

修改配置

location /aaa.html{

       rewrite "^/aaa\.html$" /bbb.html last;

       rewrite "^/bbb\.html$" /ddd.html;

输出日志:

091923147.jpg


http请求GET /aaa.html -->重写bbb.html 由于last标记rewrite不再往下执行,但执行重写到/bbb.html 后需要再次匹配location 如果有/bbb.html的location语句那么需要执行,没有故而输出了/ccc.html

【测试三】使用break 标记时:请求aaa.html

curl http://nginxtest.com:9090/aaa.html

修改配置

location /aaa.html{

       rewrite "^/aaa\.html$" /bbb.html break;

       rewrite "^/bbb\.html$" /ddd.html;

输出日志:

092011780.jpg

http请求/aaa.html-->重写bbb.html 由于break标记,退出rewrite执行,不再匹配location



四、Nginx跳转

rewrite ^/share\.action(.*)$ /share.htm?$1 last;

将请求是/share.action 后接任意字符的请求 跳转到share.hml

详解:匹配以/share.action开始后接任意字符串$表示结尾 跳转到/share.htm “?”为防止以往请求的参数会添加到新的参数后面而追加,

$1是替换(.*)里的参数


五、 Nginx 目录自动加斜线:

if (-d $request_filename){

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

}


六、 Nginx Location

1.基本语法:[和上面rewrite正则匹配语法基本一致]

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

~ 为区分大小写匹配

~* 为不区分大小写匹配

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

示例1:

location = / {

   # matches the query / only.

   # 只匹配 / 查询。

}

匹配任何查询,因为所有请求都已 / 开头。但是正则表达式规则和长的块规则将被优先和查询匹配

示例2:

location ^~ /p_w_picpaths/ {

   # matches any query beginning with /p_w_picpaths/ and halts searching,

   # so regular expressions will not be checked.

   # 匹配任何以 /p_w_picpaths/ 开头的任何查询并且停止搜索。任何正则表达式将不会被测试。

}

示例3:

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

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

   # requests to the /p_w_picpaths/ directory will be handled by

   # 匹配任何以 gif、jpg 或 jpeg 结尾的请求。

}

七、 Nginx expires

1.根据文件类型判断,添加expires

# Add expires header for static content

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

   if (-f $request_filename) {

       root /data/www/wwwroot/bbs;

       expires 1d;

       break;

   }

}

2、根据某个目录判断,添加expires

# serve static files

location ~ ^/(p_w_picpaths|javascript|js|css|flash|media|static)/ {

   root /data/www/wwwroot/down;

   expires 30d;

}

八、 Nginx 防盗链

1. 针对不同的文件类型

#Preventing hot linking of p_w_picpaths and other file types

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

   valid_referers none blocked server_names *.linuxtone.org linuxtone.org http://localhost baidu.com;

   if ($invalid_referer) {

       rewrite ^/ http://www.linuxtone.org/p_w_picpaths/default/logo.gif;

       # return 403;

   }

}

2. 针对不同的目录

location /img/ {

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

   valid_referers none blocked server_names *.linuxtone.org http://localhost baidu.com;

   if ($invalid_referer) {

       rewrite ^/ http://www.linuxtone.org/p_w_picpaths/default/logo.gif;

       #return 403;

   }

}

3. 同实现防盗链和expires的方法

#Preventing hot linking of p_w_picpaths and other file types

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

   valid_referers none blocked server_names *.linuxtone.org linuxtone.org http://localhost ;

   if ($invalid_referer) {

       rewrite ^/ http://www.linuxtone.org/p_w_picpaths/default/logo.gif;

   }

   access_log off;

   root /data/www/wwwroot/bbs;

   expires 1d;

   break;

}

九、 Nginx 访问控制

1. Nginx ×××验证

#cd /usr/local/nginx/conf

#mkdir htpasswd

/usr/local/apache2/bin/htpasswd -c /usr/local/nginx/conf/htpasswd/tongji linuxtone

#添加用户名为linuxtone

New password: (此处输入你的密码)

Re-type new password: (再次输入你的密码)

Adding password for user

http://count.linuxtone.org/tongji/data/index.html(目录存在/data/www/wwwroot/tongji/data/目录

下)

将下段配置放到虚拟主机目录,当访问http://count.linuxtone/tongji/即提示要密验证:

location ~ ^/(tongji)/ {

   root /data/www/wwwroot/count;

   auth_basic "LT-COUNT-TongJi";

   auth_basic_user_file /usr/local/nginx/conf/htpasswd/tongji;

}

2. Nginx 禁止访问某类型的文件.

如,Nginx下禁止访问*.txt文件,配置方法如下.

location ~* \.(txt|doc)$ {

   if (-f $request_filename) {

       root /data/www/wwwroot/linuxtone/test;

       #rewrite …..可以重定向到某个URL

       break;

   }

}

方法2:

location ~* \.(txt|doc)${

   root /data/www/wwwroot/linuxtone/test;

   deny all;

}

实例:

禁止访问某个目录

location ~ ^/(WEB-INF)/ {

   deny all;

}

3. 使用ngx_http_access_module限制ip访问

location / {

   deny 192.168.1.1;

   allow 192.168.1.0/24;

   allow 10.1.1.0/16;

   deny all;

}

详细参见wiki: http://wiki.codemongers.com/NginxHttpAccessModule#allow

4. Nginx 下载限制并发和速率

limit_zone linuxtone $binary_remote_addr 10m;

server {

   listen 80;

   server_name down.linuxotne.org;

   index index.html index.htm index.php;

   root /data/www/wwwroot/down;

   #Zone limit

   location / {

       limit_conn linuxtone 1;

       limit_rate 20k;

   }

   ..........

}

只允许客房端一个线程,每个线程20k.


5、除GET POST HEAD其他http方法deny

limit_except GET POST HEAD {

                deny all;

               }


5. Nginx 实现Apache一样目录列表

location / {

   autoindex on;

}

6. 上文件大小限制

主配置文件里加入如下,具体大小根据你自己的业务做调整。

client_max_body_size 10m;

十、 Nginx 日志处理

1.Nginx 日志切割

#contab -e

59 23 * * * /usr/local/sbin/logcron.sh /dev/null 2>&1

# cat /usr/local/sbin/logcron.sh

#!/bin/bash


log_dir="/data/logs"


time=`date +%Y%m%d`


/bin/mv ${log_dir}/access_linuxtone.org.log ${log_dir}/access_count.linuxtone.org.$time.log

kill -USR1 `cat /var/run/nginx.pid`


2.利用AWSTATS分析NGINX日志

设置好Nginx日志格式,仍后利用awstats进行分析.

请参考: http://bbs.linuxtone.org/thread-56-1-1.html

3. Nginx 如何不记录部分日志

日志太多,每天好几个G,少记录一些,下面的配置写到server{}段中就可以了

location ~ .*\.(js|jpg|JPG|jpeg|JPEG|css|bmp|gif|GIF)$ {

   access_log off;

}

十一、Nginx Cache服务配置

如果需要将文件缓存到本地,则需要增加如下几个子参数:

proxy_store on;

proxy_store_access user:rw group:rw all:rw;

proxy_temp_path 缓存目录;

其中,

proxy_store on 用来启用缓存到本地的功能,

proxy_temp_path 用来指定缓存在哪个目录下,如:proxy_temp_path html;

在经过上一步配置之后,虽然文件被缓存到了本地磁盘上,但每次请求仍会向远端拉取

文件,为了避免去远端拉取文件,必须修改proxy_pass:

if ( !-e $request_filename) {

   proxy_pass http://mysvr;

}

即改成有条件地去执行proxy_pass,这个条件就是当请求的文件在本地的

proxy_temp_path指定的目录下不存在时,再向后端拉取。

更多更高级的应用可以研究ncache,官方网站: http://code.google.com/p/ncache/

详细安装请参照http://bbs.linuxtone.org 应用加速版ncache相关的贴子.

十二、Nginx 负载均衡

1. Nginx 负载均衡基础知识

nginx的upstream目前支持4种方式的分配

1)、轮询(默认)

每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除。

2)、weight

指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。

2)、ip_hash

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

3)、fair(第三方)

按后端服务器的响应时间来分配请求,响应时间短的优先分配。

4)、url_hash(第三方)

2. Nginx 负载均衡实例1

upstream bbs.linuxtone.org { #定义负载均衡设备的Ip及设备状态

   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://bbs.linuxtone.org/;

每个设备的状态设置为:

a) down 表示单前的server暂时不参与负载

b) weight 默认为1.weight越大,负载的权重就越大。

c) max_fails :允许请求失败的次数默认为1.当超过最大次数时,返回proxy_next_upstream 模块定义的错误

d) fail_timeout:max_fails次失败后,暂停的时间。

e) backup: 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。

nginx支持同时设置多组的负载均衡,用来给不用的server来使用。

client_body_in_file_only 设置为On 可以讲client post过来的数据记录到文件中用来做debug

client_body_temp_path 设置记录文件的目录 可以设置最多3层目录

location 对URL进行匹配.可以进行重定向或者进行新的代理 负载均衡

3. Nginx 负载均衡实例 2

按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,后端服务器为缓

存时比较有效,也可以用作提高Squid缓存命中率.

简单的负载均等实例:

#vi nginx.conf //nginx主配置文件核心配置

.........

#loadblance my.linuxtone.org

upstream my.linuxtone.org {

   ip_hash;

   server 127.0.0.1:8080;

   server 192.168.169.136:8080;

   server 219.101.75.138:8080;

   server 192.168.169.117;

   server 192.168.169.118;

   server 192.168.169.119;

}

.........

include vhosts/linuxtone_lb.conf;

.........

# vi proxy.conf

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

client_body_buffer_size 256k;

proxy_connect_timeout 30;

proxy_send_timeout 30;

proxy_read_timeout 60;

proxy_buffer_size 4k;

proxy_buffers 4 32k;

proxy_busy_buffers_size 64k;

proxy_temp_file_write_size 64k;

proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;

proxy_max_temp_file_size 128m;

proxy_store on;

proxy_store_access user:rw group:rw all:r;

#nginx cache

#client_body_temp_path /data/nginx_cache/client_body 1 2;

proxy_temp_path /data/nginx_cache/proxy_temp 1 2;

#vi linuxtone_lb.conf

server {


   listen 80;

   server_name my.linuxtone.org;

   index index.php;

   root /data/www/wwwroot/mylinuxtone;


   if (-f $request_filename) {

       break;

   }


   if (-f $request_filename/index.php) {

       rewrite (.*) $1/index.php break;

   }


   error_page 403 http://my.linuxtone.org/member.php?m=user&a=login;


   location / {

       if ( !-e $request_filename) {

           proxy_pass http://my.linuxtone.org;

           break;

       }

       include /usr/local/nginx/conf/proxy.conf;

   }

}


十三、常见问题与错误处理

1、 400 bad request错误的原因和解决办法

配置nginx.conf相关设置如下.

client_header_buffer_size 16k;

large_client_header_buffers 4 64k;

根据具体情况调整,一般适当调整值就可以。

2、 Nginx 502 Bad Gateway错误

proxy_next_upstream error timeout invalid_header http_500 http_503;

或者尝试设置:

large_client_header_buffers 4 32k;

3、 Nginx出现的413 Request Entity Too Large错误

这个错误一般在上传文件的时候会出现,

编辑Nginx主配置文件Nginx.conf,找到http{}段,添加

client_max_body_size 10m; //设置多大根据自己的需求作调整.

如果运行php的话这个大小client_max_body_size要和php.ini中的如下值的最大值

一致或者稍大,这样就不会因为提交数据大小不一致出现的错误。

post_max_size = 10M

upload_max_filesize = 2M

4、 解决504 Gateway Time-out(nginx)

遇到这个问题是在升级discuz论坛的时候遇到的

一般看来, 这种情况可能是由于nginx默认的fastcgi进程响应的缓冲区太小造成的,

这将导致fastcgi进程被挂起, 如果你的fastcgi服务对这个挂起处理的不好, 那么最后就

极有可能导致504 Gateway Time-out

现在的网站, 尤其某些论坛有大量的回复和很多内容的, 一个页面甚至有几百K。

默认的fastcgi进程响应的缓冲区是8K, 我们可以设置大点

在nginx.conf里, 加入:

fastcgi_buffers 8 128k

这表示设置fastcgi缓冲区为8×128k

当然如果您在进行某一项即时的操作, 可能需要nginx的超时参数调大点,例如设置成60秒:

send_timeout 60;

只是调整了这两个参数, 结果就是没有再显示那个超时, 可以说效果不错, 但是也

可能是由于其他的原因, 目前关于nginx的资料不是很多, 很多事情都需要长期的经验

累计才有结果, 期待您的发现哈!

5、 如何使用Nginx Proxy

朋友一台服务器运行tomcat 为8080端口,IP:192.168.1.2:8080,另一台机器

IP:192.168.1.8. 朋友想通过访问http://192.168.1.8即可访问tomcat服务.配置如下:

在192.168.1.8的nginx.conf上配置如下:

server {

   listen 80;

   server_name java.linuxtone.org

   location / {

       proxy_pass http://192.168.1.2:8080;

       include /usr/local/nginx/conf/proxy.conf;

   }

}

6、 如何关闭Nginx的LOG

access_log /dev/null;

error_log /dev/null;