<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
<title><![CDATA[刘新修]]></title> 
<link>http://liuxinxiu.com:80/index.php</link> 
<description><![CDATA[刘新修的个人博客 (Liuxinxiu'S Blog)]]></description> 
<language>zh-cn</language> 
<copyright><![CDATA[刘新修]]></copyright>
<item>
<link>http://liuxinxiu.com:80/nginx_manual/</link>
<title><![CDATA[【转载】Nginx中文手册（技术指南第二版）]]></title> 
<author>刘新修 &lt;admin@yourname.com&gt;</author>
<category><![CDATA[web服务器]]></category>
<pubDate>Fri, 24 Jun 2011 01:36:23 +0000</pubDate> 
<guid>http://liuxinxiu.com:80/nginx_manual/</guid> 
<description>
<![CDATA[ 
	<p>Nginx 常见应用技术指南[Nginx Tips] 第二版</p><p>目 录</p><p>一、 Nginx 基础知识<br />二、 Nginx 安装及调试<br />三、 Nginx Rewrite<br />四、 Nginx Redirect<br />五、 Nginx 目录自动加斜线:<br />六、 Nginx Location<br />七、 Nginx expires<br />八、 Nginx 防盗链<br />九、 Nginx 访问控制<br />十、 Nginx日志处理<br />十一、 Nginx Cache<br />十二、 Nginx 负载均衡<br />十三、 Nginx简单优化<br />十四、 如何构建高性能的LEMP环境<br />十五、 Nginx服务监控<br />十六、 常见问题与错误处理.<br />十七、 相关资源下载</p><p>【前言】：</p><p>编写此技术指南在于推广普及NGINX在国内的使用，更方便的帮助大家了解和掌握NGINX<br />的一些使用技巧。本指南很多技巧来自于网络和工作中或网络上朋友们问我的问题.在此对<br />网络上愿意分享的朋友们表示感谢和致意！欢迎大家和我一起丰富本技术指南提出更好的建<br />议！请朋友们关注: http://www.linuxtone.org 技术分享社区! 互想学习共同进步!</p><p><strong>一、 Nginx 基础知识</strong></p><p>1、简介<br />Nginx (&quot;engine x&quot;) 是一个高性能的 HTTP 和 反向代理 服务器，也是一个 IMAP/POP3/SMTP 代理服<br />务器。 Nginx 是由 Igor Sysoev 为俄罗斯访问量第二的 Rambler.ru 站点开发的，它已经在该站点运行超<br />过两年半了。Igor 将源代码以类BSD许可证的形式发布。尽管还是测试版，但是，Nginx 已经因为它的稳<br />定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名了。</p><p>更多的请见官方wiki: http://wiki.codemongers.com/</p><p>2、 Nginx的优点<br />nginx做为HTTP服务器，有以下几项基本特性：<br />1) 处理静态文件，索引文件以及自动索引；打开文件描述符缓冲．<br />2) 无缓存的反向代理加速，简单的负载均衡和容错．<br />3) FastCGI，简单的负载均衡和容错．<br />4) 模块化的结构。包括gzipping, byte ranges, chunked responses, 以及 SSI-filter等filter。<br />如果由FastCGI或其它代理服务器处理单页中存在的多个SSI，则这项处理可以并行运行，而不<br />需要相互等待。<br />5) 支持SSL 和 TLS SNI．<br />Nginx专为性能优化而开发，性能是其最重要的考量, 实现上非常注重效率 。它支持内核Poll模型，<br />能经受高负载的考验, 有报告表明能支持高达 50,000 个并发连接数。</p><p>Nginx具有很高的稳定性。其它HTTP服务器，当遇到访问的峰值，或者有人恶意发起慢速连接时，<br />也很可能会导致服务器物理内存耗尽频繁交换，失去响应，只能重启服务器。例如当前apache一旦上到<br />200个以上进程，web响应速度就明显非常缓慢了。而Nginx采取了分阶段资源分配技术，使得它的CPU与<br />内存占用率非常低。nginx官方表示保持10,000个没有活动的连接，它只占2.5M内存，所以类似DOS这<br />样的攻击对nginx来说基本上是毫无用处的。就稳定性而言, nginx比lighthttpd更胜一筹。</p><p>Nginx支持热部署。它的启动特别容易, 并且几乎可以做到7*24不间断运行，即使运行数个月也不<br />需要重新启动。你还能够在不间断服务的情况下，对软件版本进行进行升级。</p><p>Nginx采用master-slave模型, 能够充分利用SMP的优势，且能够减少工作进程在磁盘I/O的阻<br />塞延迟。当采用select()/poll()调用时，还可以限制每个进程的连接数。</p><p>Nginx代码质量非常高，代码很规范， 手法成熟， 模块扩展也很容易。特别值得一提的是强大<br />的Upstream与Filter链。 Upstream为诸如reverse proxy, 与其他服务器通信模块的编写奠定了很好的<br />基础。而Filter链最酷的部分就是各个filter不必等待前一个filter执行完毕。它可以把前一个filter<br />的输出做为当前filter的输入，这有点像Unix的管线。这意味着，一个模块可以开始压缩从后端服务器<br />发送过来的请求，且可以在模块接收完后端服务器的整个请求之前把压缩流转向客户端。</p><p>Nginx采用了一些os提供的最新特性如对sendfile (Linux 2.2+)，accept-filter (FreeBSD<br />4.1+)，TCP_DEFER_ACCEPT (Linux 2.4+) 的支持，从而大大提高了性能</p><p><strong>二、 Nginx 安装及调试</strong></p><p>1、Pcre 安装</p><div class="hl-surround"><div class="hl-main">./configure<br />make &amp;&amp; make install<br />cd ../</div></div><p>2. nginx 编译安装</p><div class="hl-surround"><div class="hl-main">/configure --user=www --group=www --prefix=/usr/local/nginx/ --with-http_stub_status_module<br />--with-openssl=/usr/local/openssl<br /><br />make &amp;&amp; make install</div></div><p>更详细的模块定制与安装请参照官方wiki.</p><p>3、Nginx 配置文件测试：</p><div class="hl-surround"><div class="hl-main"># /usr/local/nginx/sbin/nginx -t //Debug 配置文件的关键命令需要重点撑握.</div></div><blockquote><p>2008/12/16 09:08:35 [info] 28412#0: the configuration file /usr/local/nginx/conf/nginx.conf<br />syntax is ok<br />2008/12/16 09:08:35 [info] 28412#0: the configuration file /usr/local/nginx/conf/nginx.conf was<br />tested successfully</p></blockquote><p>3、 Nginx 启动：</p><div class="hl-surround"><div class="hl-main"># /usr/local/nginx/sbin/nginx</div></div><p>4、 Nginx 配置文件修改重新加载：</p><div class="hl-surround"><div class="hl-main"># kill -HUP `cat /usr/local/nginx/logs/nginx.pid `</div></div><p>三、 Nginx Rewrite</p><p>1. Nginx Rewrite 基本标记(flags)<br />last - 基本上都用这个Flag。<br />※相当于Apache里的[L]标记，表示完成rewrite，不再匹配后面的规则<br />break - 中止Rewirte，不再继续匹配<br />redirect - 返回临时重定向的HTTP状态302<br />permanent - 返回永久重定向的HTTP状态301<br />※原有的url支持正则 重写的url不支持正则</p><p>2. 正则表达式匹配，其中：<br /><strong>~ </strong>为区分大小写匹配<br /><strong>~*</strong> 为不区分大小写匹配<br /><strong>!~</strong> 和 <strong>!~* </strong>分别为区分大小写不匹配及不区分大小写不匹配</p><p>3. 文件及目录匹配，其中：<br /><strong>-f </strong>和 <strong>!-f</strong> 用来判断是否存在文件<br /><strong>-d</strong> 和 <strong>!-d</strong> 用来判断是否存在目录<br /><strong>-e</strong> 和 <strong>!-e</strong> 用来判断是否存在文件或目录<br /><strong>-x </strong>和 <strong>!-x</strong> 用来判断文件是否可执行</p><p>3. Nginx 的一些可用的全局变量，可用做条件判断：</p><div class="hl-surround"><div class="hl-main">$args<br />$content_length<br />$content_type<br />$document_root<br />$document_uri<br />$host<br />$http_user_agent<br />$http_cookie<br />$limit_rate<br />$request_body_file<br />$request_method<br />$remote_addr<br />$remote_port<br />$remote_user<br />$request_filename<br />$request_uri<br />$query_string<br />$scheme<br />$server_protocol<br />$server_addr<br />$server_name<br />$server_port<br />$uri</div></div><p>四、 Nginx Redirect</p><p>将所有linuxtone.org与netseek.linuxtone.org域名全部自跳转到http://www.linuxtone.org</p><div class="hl-surround"><div class="hl-main">server &#123;<br />&nbsp;&nbsp; &nbsp;listen 80;<br />&nbsp;&nbsp; &nbsp;server_name linuxtone.org netseek.linuxtone.org;<br />&nbsp;&nbsp; &nbsp;index index.html index.php;<br />&nbsp;&nbsp; &nbsp;root /data/www/wwwroot;<br />&nbsp;&nbsp; &nbsp;if ($host !~ &quot;^www&#92;.linxtone&#92;.org$&quot;) &#123;<br />&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;rewrite ^(.*) http://www.linuxtone.org$1 redirect;<br />&nbsp;&nbsp; &nbsp;&#125;<br />&nbsp;&nbsp; &nbsp;.....................<br />&#125;</div></div><p>五、 Nginx 目录自动加斜线:</p><div class="hl-surround"><div class="hl-main">if (-d $request_filename)&#123;<br />&nbsp;&nbsp; &nbsp;rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;<br />&#125;</div></div><p>六、 Nginx Location</p><p>1．基本语法:[和上面rewrite正则匹配语法基本一致]<br />location [=&#124;~&#124;~*&#124;^~] /uri/ &#123; &hellip; &#125;<br /><strong>~</strong> 为区分大小写匹配<br /><strong>~*</strong> 为不区分大小写匹配<br /><strong>!~</strong> 和 <strong>!~*</strong> 分别为区分大小写不匹配及不区分大小写不匹配</p><p>示例1:</p><div class="hl-surround"><div class="hl-main">location = / &#123;<br />&nbsp;&nbsp; &nbsp;# matches the query / only.<br />&nbsp;&nbsp; &nbsp;# 只匹配 / 查询。<br />&#125;</div></div><p>匹配任何查询，因为所有请求都已 / 开头。但是正则表达式规则和长的块规则将被优先和查询匹配</p><p>示例2:</p><div class="hl-surround"><div class="hl-main">location ^~ /images/ &#123;<br />&nbsp;&nbsp; &nbsp;# matches any query beginning with /images/ and halts searching,<br />&nbsp;&nbsp; &nbsp;# so regular expressions will not be checked.<br />&nbsp;&nbsp; &nbsp;# 匹配任何以 /images/ 开头的任何查询并且停止搜索。任何正则表达式将不会被测试。<br />&#125;</div></div><p>示例3:</p><div class="hl-surround"><div class="hl-main">location ~* &#92;.(gif&#124;jpg&#124;jpeg)$ &#123;<br />&nbsp;&nbsp; &nbsp;# matches any request ending in gif, jpg, or jpeg. However, all<br />&nbsp;&nbsp; &nbsp;# requests to the /images/ directory will be handled by<br />&nbsp;&nbsp; &nbsp;# 匹配任何以 gif、jpg 或 jpeg 结尾的请求。<br />&#125;</div></div><p>七、 Nginx expires</p><p>1．根据文件类型判断，添加expires</p><div class="hl-surround"><div class="hl-main"># Add expires header for static content<br />location ~* &#92;.(js&#124;css&#124;jpg&#124;jpeg&#124;gif&#124;png&#124;swf)$ &#123;<br />&nbsp;&nbsp; &nbsp;if (-f $request_filename) &#123;<br />&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;root /data/www/wwwroot/bbs;<br />&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;expires 1d;<br />&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;break;<br />&nbsp;&nbsp; &nbsp;&#125;<br />&#125;</div></div><p>2、根据某个目录判断，添加expires</p><div class="hl-surround"><div class="hl-main"># serve static files<br />location ~ ^/(images&#124;javascript&#124;js&#124;css&#124;flash&#124;media&#124;static)/ &#123;<br />&nbsp;&nbsp; &nbsp;root /data/www/wwwroot/down;<br />&nbsp;&nbsp; &nbsp;expires 30d;<br />&#125;</div></div><p>八、 Nginx 防盗链</p><p>1. 针对不同的文件类型</p><div class="hl-surround"><div class="hl-main">#Preventing hot linking of images and other file types<br />location ~* ^.+&#92;.(gif&#124;jpg&#124;png&#124;swf&#124;flv&#124;rar&#124;zip)$ &#123;<br />&nbsp;&nbsp; &nbsp;valid_referers none blocked server_names *.linuxtone.org linuxtone.org http://localhost baidu.com;<br />&nbsp;&nbsp; &nbsp;if ($invalid_referer) &#123;<br />&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;rewrite ^/ http://www.linuxtone.org/images/default/logo.gif;<br />&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;# return 403;<br />&nbsp;&nbsp; &nbsp;&#125;<br />&#125;</div></div><p>2. 针对不同的目录</p><div class="hl-surround"><div class="hl-main">location /img/ &#123;<br />&nbsp;&nbsp; &nbsp;root /data/www/wwwroot/bbs/img/;<br />&nbsp;&nbsp; &nbsp;valid_referers none blocked server_names *.linuxtone.org http://localhost baidu.com;<br />&nbsp;&nbsp; &nbsp;if ($invalid_referer) &#123;<br />&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;rewrite ^/ http://www.linuxtone.org/images/default/logo.gif;<br />&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;#return 403;<br />&nbsp;&nbsp; &nbsp;&#125;<br />&#125;</div></div><p>3. 同实现防盗链和expires的方法</p><div class="hl-surround"><div class="hl-main">#Preventing hot linking of images and other file types<br />location ~* ^.+&#92;.(gif&#124;jpg&#124;png&#124;swf&#124;flv&#124;rar&#124;zip)$ &#123;<br />&nbsp;&nbsp; &nbsp;valid_referers none blocked server_names *.linuxtone.org linuxtone.org http://localhost ;<br />&nbsp;&nbsp; &nbsp;if ($invalid_referer) &#123;<br />&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;rewrite ^/ http://www.linuxtone.org/images/default/logo.gif;<br />&nbsp;&nbsp; &nbsp;&#125;<br />&nbsp;&nbsp; &nbsp;access_log off;<br />&nbsp;&nbsp; &nbsp;root /data/www/wwwroot/bbs;<br />&nbsp;&nbsp; &nbsp;expires 1d;<br />&nbsp;&nbsp; &nbsp;break;<br />&#125;</div></div><p>九、 Nginx 访问控制</p><p>1. Nginx 身份证验证</p><div class="hl-surround"><div class="hl-main">#cd /usr/local/nginx/conf<br />#mkdir htpasswd<br />/usr/local/apache2/bin/htpasswd -c /usr/local/nginx/conf/htpasswd/tongji linuxtone</div></div><p>#添加用户名为linuxtone<br />New password: (此处输入你的密码)<br />Re-type new password: (再次输入你的密码)<br />Adding password for user</p><p>http://count.linuxtone.org/tongji/data/index.html(目录存在/data/www/wwwroot/tongji/data/目录</p><p>下)</p><p>将下段配置放到虚拟主机目录，当访问http://count.linuxtone/tongji/即提示要密验证:</p><div class="hl-surround"><div class="hl-main">location ~ ^/(tongji)/ &#123;<br />&nbsp;&nbsp; &nbsp;root /data/www/wwwroot/count;<br />&nbsp;&nbsp; &nbsp;auth_basic &quot;LT-COUNT-TongJi&quot;;<br />&nbsp;&nbsp; &nbsp;auth_basic_user_file /usr/local/nginx/conf/htpasswd/tongji;<br />&#125;</div></div><p>2. Nginx 禁止访问某类型的文件.</p><p>如，Nginx下禁止访问*.txt文件，配置方法如下.</p><div class="hl-surround"><div class="hl-main">location ~* &#92;.(txt&#124;doc)$ &#123;<br />&nbsp;&nbsp; &nbsp;if (-f $request_filename) &#123;<br />&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;root /data/www/wwwroot/linuxtone/test;<br />&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;#rewrite &hellip;..可以重定向到某个URL<br />&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;break;<br />&nbsp;&nbsp; &nbsp;&#125;<br />&#125;</div></div><p>方法2:</p><div class="hl-surround"><div class="hl-main">location ~* &#92;.(txt&#124;doc)$&#123;<br />&nbsp;&nbsp; &nbsp;root /data/www/wwwroot/linuxtone/test;<br />&nbsp;&nbsp; &nbsp;deny all;<br />&#125;</div></div><p>实例:<br />禁止访问某个目录</p><div class="hl-surround"><div class="hl-main">location ~ ^/(WEB-INF)/ &#123;<br />&nbsp;&nbsp; &nbsp;deny all;<br />&#125;</div></div><p>3. 使用ngx_http_access_module限制ip访问</p><div class="hl-surround"><div class="hl-main">location / &#123;<br />&nbsp;&nbsp; &nbsp;deny 192.168.1.1;<br />&nbsp;&nbsp; &nbsp;allow 192.168.1.0/24;<br />&nbsp;&nbsp; &nbsp;allow 10.1.1.0/16;<br />&nbsp;&nbsp; &nbsp;deny all;<br />&#125;</div></div><p>详细参见wiki: http://wiki.codemongers.com/NginxHttpAccessModule#allow</p><p>4. Nginx 下载限制并发和速率</p><div class="hl-surround"><div class="hl-main">limit_zone linuxtone $binary_remote_addr 10m;<br />server &#123;<br />&nbsp;&nbsp; &nbsp;listen 80;<br />&nbsp;&nbsp; &nbsp;server_name down.linuxotne.org;<br />&nbsp;&nbsp; &nbsp;index index.html index.htm index.php;<br />&nbsp;&nbsp; &nbsp;root /data/www/wwwroot/down;<br />&nbsp;&nbsp; &nbsp;#Zone limit<br />&nbsp;&nbsp; &nbsp;location / &#123;<br />&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;limit_conn linuxtone 1;<br />&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;limit_rate 20k;<br />&nbsp;&nbsp; &nbsp;&#125;<br />&nbsp;&nbsp; &nbsp;..........<br />&#125;</div></div><p>只允许客房端一个线程,每个线程20k.</p><p><strong>【注】limit_zone linuxtone $binary_remote_addr 10m; 这个可以定义在主的</strong></p><p>5. Nginx 实现Apache一样目录列表</p><div class="hl-surround"><div class="hl-main">location / &#123;<br />&nbsp;&nbsp; &nbsp;autoindex on;<br />&#125;</div></div><p>6. 上文件大小限制<br />主配置文件里加入如下，具体大小根据你自己的业务做调整。</p><div class="hl-surround"><div class="hl-main">client_max_body_size 10m;</div></div><p>十、 Nginx 日志处理</p><p>1.Nginx 日志切割</p><div class="hl-surround"><div class="hl-main">#contab -e<br />59 23 * * * /usr/local/sbin/logcron.sh /dev/null 2&gt;&amp;1</div></div><p># cat /usr/local/sbin/logcron.sh</p><div class="hl-surround"><div class="hl-main">#!/bin/bash<br /><br />log_dir=&quot;/data/logs&quot;<br /><br />time=`date +%Y%m%d`<br /><br />/bin/mv $&#123;log_dir&#125;/access_linuxtone.org.log $&#123;log_dir&#125;/access_count.linuxtone.org.$time.log</div></div><div class="hl-surround"><div class="hl-main">kill -USR1 `cat /var/run/nginx.pid`</div></div><p>更多的日志分析与处理就关注(同时欢迎你参加讨论):http://bbs.linuxtone.org/forum-8-1.html</p><p>2.利用AWSTATS分析NGINX日志<br />设置好Nginx日志格式,仍后利用awstats进行分析.<br />请参考: http://bbs.linuxtone.org/thread-56-1-1.html</p><p>3. Nginx 如何不记录部分日志<br />日志太多，每天好几个G，少记录一些，下面的配置写到server&#123;&#125;段中就可以了</p><div class="hl-surround"><div class="hl-main">location ~ .*&#92;.(js&#124;jpg&#124;JPG&#124;jpeg&#124;JPEG&#124;css&#124;bmp&#124;gif&#124;GIF)$ &#123;<br />&nbsp;&nbsp; &nbsp;access_log off;<br />&#125;</div></div><p>十一、Nginx Cache服务配置</p><p>如果需要将文件缓存到本地，则需要增加如下几个子参数：</p><div class="hl-surround"><div class="hl-main">proxy_store on;<br />proxy_store_access user:rw group:rw all:rw;<br />proxy_temp_path 缓存目录;</div></div><p>其中，<br />proxy_store on 用来启用缓存到本地的功能，<br />proxy_temp_path 用来指定缓存在哪个目录下，如：proxy_temp_path html;</p><p>在经过上一步配置之后，虽然文件被缓存到了本地磁盘上，但每次请求仍会向远端拉取<br />文件，为了避免去远端拉取文件，必须修改proxy_pass：</p><div class="hl-surround"><div class="hl-main">if ( !-e $request_filename) &#123;<br />&nbsp;&nbsp; &nbsp;proxy_pass http://mysvr;<br />&#125;</div></div><p>即改成有条件地去执行proxy_pass，这个条件就是当请求的文件在本地的<br />proxy_temp_path指定的目录下不存在时，再向后端拉取。</p><p>更多更高级的应用可以研究ncache，官方网站: http://code.google.com/p/ncache/</p><p>详细安装请参照http://bbs.linuxtone.org 应用加速版ncache相关的贴子.</p><p>十二、Nginx 负载均衡</p><p>1. Nginx 负载均衡基础知识</p><p>nginx的upstream目前支持4种方式的分配</p><p>1)、轮询（默认）<br />每个请求按时间顺序逐一分配到不同的后端服务器，如果后端服务器down掉，能自动剔除。</p><p>2)、weight<br />指定轮询几率，weight和访问比率成正比，用于后端服务器性能不均的情况。</p><p>2)、ip_hash<br />每个请求按访问ip的hash结果分配，这样每个访客固定访问一个后端服务器，可以解决session的问题。</p><p>3)、fair（第三方）<br />按后端服务器的响应时间来分配请求，响应时间短的优先分配。</p><p>4)、url_hash（第三方）</p><p>2. Nginx 负载均衡实例1</p><div class="hl-surround"><div class="hl-main">upstream bbs.linuxtone.org &#123; #定义负载均衡设备的Ip及设备状态<br />&nbsp;&nbsp; &nbsp;server 127.0.0.1:9090 down;<br />&nbsp;&nbsp; &nbsp; server 127.0.0.1:8080 weight=2;<br />&nbsp;&nbsp; &nbsp; server 127.0.0.1:6060;<br />&nbsp;&nbsp; &nbsp; server 127.0.0.1:7070 backup;<br />&#125;</div></div><p>在需要使用负载均衡的server中增加</p><div class="hl-surround"><div class="hl-main">proxy_pass http://bbs.linuxtone.org/;</div></div><p>每个设备的状态设置为:<br />a) down 表示单前的server暂时不参与负载<br />b) weight 默认为1.weight越大，负载的权重就越大。<br />c) max_fails ：允许请求失败的次数默认为1.当超过最大次数时，返回proxy_next_upstream 模块定义的错误<br />d) fail_timeout:max_fails次失败后，暂停的时间。<br />e) backup： 其它所有的非backup机器down或者忙的时候，请求backup机器。所以这台机器压力会最轻。</p><p>nginx支持同时设置多组的负载均衡，用来给不用的server来使用。</p><p>client_body_in_file_only 设置为On 可以讲client post过来的数据记录到文件中用来做debug<br />client_body_temp_path 设置记录文件的目录 可以设置最多3层目录<br />location 对URL进行匹配.可以进行重定向或者进行新的代理 负载均衡</p><p>3. Nginx 负载均衡实例 2<br />按访问url的hash结果来分配请求，使每个url定向到同一个后端服务器，后端服务器为缓<br />存时比较有效,也可以用作提高Squid缓存命中率.</p><p>简单的负载均等实例:<br />#vi nginx.conf //nginx主配置文件核心配置<br />.........</p><div class="hl-surround"><div class="hl-main">#loadblance my.linuxtone.org<br />upstream my.linuxtone.org &#123;<br />&nbsp;&nbsp; &nbsp;ip_hash;<br />&nbsp;&nbsp; &nbsp;server 127.0.0.1:8080;<br />&nbsp;&nbsp; &nbsp;server 192.168.169.136:8080;<br />&nbsp;&nbsp; &nbsp;server 219.101.75.138:8080;<br />&nbsp;&nbsp; &nbsp;server 192.168.169.117;<br />&nbsp;&nbsp; &nbsp;server 192.168.169.118;<br />&nbsp;&nbsp; &nbsp;server 192.168.169.119;<br />&#125;<br />.........<br />include vhosts/linuxtone_lb.conf;<br />.........</div></div><p># vi proxy.conf</p><div class="hl-surround"><div class="hl-main">proxy_redirect off;<br />proxy_set_header Host $host;<br />proxy_set_header X-Real-IP $remote_addr;<br />proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br />client_max_body_size 50m;<br />client_body_buffer_size 256k;<br />proxy_connect_timeout 30;<br />proxy_send_timeout 30;<br />proxy_read_timeout 60;<br />proxy_buffer_size 4k;<br />proxy_buffers 4 32k;<br />proxy_busy_buffers_size 64k;<br />proxy_temp_file_write_size 64k;<br />proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;<br />proxy_max_temp_file_size 128m;<br />proxy_store on;<br />proxy_store_access user:rw group:rw all:r;<br />#nginx cache<br />#client_body_temp_path /data/nginx_cache/client_body 1 2;<br />proxy_temp_path /data/nginx_cache/proxy_temp 1 2;</div></div><p>#vi linuxtone_lb.conf</p><div class="hl-surround"><div class="hl-main">server &#123;<br /><br />&nbsp;&nbsp; &nbsp;listen 80;<br />&nbsp;&nbsp; &nbsp;server_name my.linuxtone.org;<br />&nbsp;&nbsp; &nbsp;index index.php;<br />&nbsp;&nbsp; &nbsp;root /data/www/wwwroot/mylinuxtone;<br /><br />&nbsp;&nbsp; &nbsp;if (-f $request_filename) &#123;<br />&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;break;<br />&nbsp;&nbsp; &nbsp;&#125;<br /><br />&nbsp;&nbsp; &nbsp;if (-f $request_filename/index.php) &#123;<br />&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;rewrite (.*) $1/index.php break;<br />&nbsp;&nbsp; &nbsp;&#125;<br /><br />&nbsp;&nbsp; &nbsp;error_page 403 http://my.linuxtone.org/member.php?m=user&amp;a=login;<br /><br />&nbsp;&nbsp; &nbsp;location / &#123;<br />&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;if ( !-e $request_filename) &#123;<br />&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;proxy_pass http://my.linuxtone.org;<br />&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;break;<br />&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;&#125;<br />&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;include /usr/local/nginx/conf/proxy.conf;<br />&nbsp;&nbsp; &nbsp;&#125;<br />&#125;</div></div><p>十三、Nginx简单优化</p><p>1. 减小nginx编译后的文件大小 (Reduce file size of nginx)<br />默认的nginx编译选项里居然是用debug模式(-g)的（debug模式会插入很多跟踪和<br />ASSERT之类），编译以后一个nginx有好几兆。去掉nginx的debug模式编译，编译以<br />后只有几百K</p><p>在 <strong>auto/cc/gcc</strong>，最后几行有：</p><div class="hl-surround"><div class="hl-main"># debug<br />CFLAGS=&rdquo;$CFLAGS -g&rdquo;</div></div><p>注释掉或删掉这几行，重新编译即可。</p><p>2. 修改Nginx的header伪装服务器</p><p>1) 修改<strong>nginx.h</strong></p><div class="hl-surround"><div class="hl-main">#vi nginx-0.7.30/src/core/nginx.h<br />#define NGINX_VERSION &quot;1.8&quot;<br />#define NGINX_VER &quot;LTWS/&quot; NGINX_VERSION<br />#define NGINX_VAR &quot;NGINX&quot;<br />#define NGX_OLDPID_EXT &quot;.oldbin&quot;</div></div><p>2) 修改nginx_http_header_filter_module<br />#vi nginx-0.7.30/src/http/ngx_http_header_filter_module.c<br />将如下</p><div class="hl-surround"><div class="hl-main">static char ngx_http_server_string[] = &quot;Server: nginx&quot; CRLF;</div></div><p>修改为</p><div class="hl-surround"><div class="hl-main">static char ngx_http_server_string[] = &quot;Server: LTWS&quot; CRLF;</div></div><p>a) 修改nginx_http_header_filter_module<br />#vi nginx-0.7.30/src/http/ngx_http_special_response.c<br />将如下：</p><div class="hl-surround"><div class="hl-main">static u_char ngx_http_error_full_tail[] =<br />&quot;&lt;hr&gt;&lt;center&gt;&quot; NGINX_VER &quot;&lt;/center&gt;&quot; CRLF<br />&quot;&lt;/body&gt;&quot; CRLF<br />&quot;&lt;/html&gt;&quot; CRLF<br />;<br /><br />static u_char ngx_http_error_tail[] =<br />&quot;&lt;hr&gt;&lt;center&gt;nginx&lt;/center&gt;&quot; CRLF<br />&quot;&lt;/body&gt;&quot; CRLF<br />&quot;&lt;/html&gt;&quot; CRLF<br />;</div></div><p>修改为:</p><div class="hl-surround"><div class="hl-main">static u_char ngx_http_error_full_tail[] =<br />&quot;&lt;center&gt; &quot;NGINX_VER&quot; &lt;/center&gt;&quot; CRLF<br />&quot;&lt;hr&gt;&lt;center&gt;http://www.linuxtone.org&lt;/center&gt;&quot; CRLF<br />&quot;&lt;/body&gt;&quot; CRLF<br />&quot;&lt;/html&gt;&quot; CRLF<br />;<br /><br />static u_char ngx_http_error_tail[] =<br />&quot;&lt;hr&gt;&lt;center&gt;LTWS&lt;/center&gt;&quot; CRLF<br />&quot;&lt;/body&gt;&quot; CRLF<br />&quot;&lt;/html&gt;&quot; CRLF<br />;</div></div><p>修改后重新编译一下环境,</p><p>404错误的时候显示效果图（如果没有指定错误页的话）：</p><p>利用curl命令查看服务器header</p><p>3. 为特定的CPU指定CPU类型编译优化.</p><p>默认nginx使用的GCC编译参数是-O</p><p>需要更加优化可以使用以下两个参数</p><div class="hl-surround"><div class="hl-main">--with-cc-opt='-O3' &#92;<br /><br />--with-cpu-opt=opteron &#92;</div></div><p>使得编译针对特定CPU以及增加GCC的优化.</p><p>此方法仅对性能有所改善并不会有很大的性能提升，供朋友们参考.</p><p>CPUD类型确定:</p><div class="hl-surround"><div class="hl-main"># cat /proc/cpuinfo &#124; grep &quot;model name&quot;</div></div><p>编译优化参数参考：http://en.gentoo-wiki.com/wiki/Safe_Cflags</p><p>4. Tcmalloc优化Nginx 性能</p><div class="hl-surround"><div class="hl-main"># wget http://download.savannah.gnu.org/releases/libunwind/libunwind-0.99-alpha.tar.gz<br /># tar zxvf libunwind-0.99-alpha.tar.gz<br /># cd libunwind-0.99-alpha/<br /># CFLAGS=-fPIC ./configure<br /># make CFLAGS=-fPIC<br /># make CFLAGS=-fPIC install<br /># wget http://google-perftools.googlecode.com/files/google-perftools-0.98.tar.gz<br /># tar zxvf google-perftools-0.98.tar.gz<br /># cd google-perftools-0.98/<br /># ./configure<br /># make &amp;&amp; make install<br /># echo &quot;/usr/local/lib&quot; &gt; /etc/ld.so.conf.d/usr_local_lib.conf<br /># ldconfig<br /># lsof -n &#124; grep tcmalloc</div></div><p>编译nginx 加载google_perftools_module:</p><div class="hl-surround"><div class="hl-main">./configure --with-google_perftools_module</div></div><p>在主配置文件加入nginx.conf 添加:</p><div class="hl-surround"><div class="hl-main">google_perftools_profiles /path/to/profile;</div></div><p>5. 内核参数优化<br /># vi /etc/sysctl.conf</p><div class="hl-surround"><div class="hl-main">#在末尾增加以下内容：<br />net.ipv4.tcp_fin_timeout = 30<br />net.ipv4.tcp_keepalive_time = 300<br />net.ipv4.tcp_syncookies = 1<br />net.ipv4.tcp_tw_reuse = 1<br />net.ipv4.tcp_tw_recycle = 1<br />net.ipv4.ip_local_port_range = 5000 65000</div></div><p>#使配置立即生效<br />/sbin/sysctl -p</p><p>十四、如何构建高性的LEMP</p><p>请参见: http://www.linuxtone.org/lemp/lemp.pdf</p><p>1、 提供完整的配置脚本下载：http://www.linuxtone.org/lemp/scripts.tar.gz<br />2、 提供NGINX常见配置范例含(虚拟主机，防盗链，Rewrite,访问控制，负载均衡Discuz相关程序静态化及等等),你只要稍稍修改即可线上应用。<br />3、将原版的xcache替换成EA，并提供相关简单调优脚本及配置文件。</p><p>更多的及更新资料请关注: http://www.linuxtone.org</p><p>十五、Nginx监控</p><p>1、 RRDTOOL+Perl脚本画图监控<br />先安装好rrdtool ，关于rrdtool本文不作介绍，具体安装请参照linuxtone监控版块.</p><div class="hl-surround"><div class="hl-main">#cd /usr/local/sbnin<br />#wget http://blog.kovyrin.net/files/mrtg/rrd_nginx.pl.txt<br />#mv rrd_nginx.pl.txt rrd_nginx.pl<br />#chmod a+x rrd_nginx.pl</div></div><p>#vi rrd_nginx.pl //配置脚本文件设置好路径</p><div class="hl-surround"><div class="hl-main">#!/usr/bin/perl<br />use RRDs;<br />use LWP::UserAgent;<br /><br /># define location of rrdtool databases<br />my $rrd = '/data/www/wwwroot/nginx/rrd';<br /><br /># define location of images<br />my $img = '/data/www/wwwroot/nginx/html';<br /><br /># define your nginx stats URL<br />my $URL = &quot;http:// 219.32.205.13/nginx_status&quot;;<br />&hellip;&hellip;&hellip;&hellip;</div></div><p>【注】根据自己具体的状况修改相应的路径.</p><p>#crontab &ndash;e //加入如下</p><div class="hl-surround"><div class="hl-main">* * * * * /usr/local/sbin/rrd_nginx.pl</div></div><p>重启crond后，通过配置nginx虚拟主机指到/data/www/wwwroot/nginx/html目录，通过crond<br />自动执行perl脚本会生成很多图片.</p><p>http://xxx/connections-day.png即可看到服务器状态图。</p><p>2、 官方Nginx-rrd 监控服务（多虚拟主机）（推荐）<br />网址：http://www.nginx.eu/nginx-rrd.html</p><p>此解决方案其实是基于上述监控方案的一个改进和增强，同样先安装好rrdtool这个画图工<br />具和相应的perl模块再做如下操作：</p><div class="hl-surround"><div class="hl-main"># yum install perl-HTML*</div></div><p>先建立好生成的库存和图片存放录</p><div class="hl-surround"><div class="hl-main">#mkdir -p /data/www/wwwroot/nginx/&#123;rrd,html&#125;<br />#cd /usr/local/sbin<br />#wget http://www.nginx.eu/nginx-rrd/nginx-rrd-0.1.4.tgz<br />#tar zxvf nginx-rrd-0.1.4.tgz<br />#cd nginx-rrd-0.1.4<br />#cd etc/<br />#cp nginx-rrd.conf /etc<br />#cd etc/cron.d<br />#cp nginx-rrd.cron /etc/cron.d<br />#cd /usr/local/src/nginx-rrd-0.1.4/html<br /># cp index.php /data/www/wwwroot/nginx/html/<br />#cd /usr/local/src/nginx-rrd-0.1.4/usr/sbin<br />#cp * /usr/sbin/</div></div><p>#vi /etc/nginx-rrd.conf</p><div class="hl-surround"><div class="hl-main">#####################################################<br />#<br /># dir where rrd databases are stored<br /><br />RRD_DIR=&quot;/data/www/wwwroot/nginx/rrd&quot;;<br /><br /># dir where png images are presented<br /><br />WWW_DIR=&quot;/data/www/wwwroot/nginx/html&quot;;<br /><br /># process nice level<br /><br />NICE_LEVEL=&quot;-19&quot;;<br /><br /># bin dir<br /><br />BIN_DIR=&quot;/usr/sbin&quot;;<br /><br /># servers to test<br /><br /># server_utl;server_name<br /><br />SERVERS_URL=&quot;http://219.32.205.13/nginx_status;219.32.205.13</div></div><p>http://www.linuxtone.org/nginx_status;www.linuxtone.org&quot;&quot; //根据你的具体情况做调整.</p><p>SEVERS_URL 格式 http://domain1/nginx_status;domain1 http://domain2/nginx_status;domain2</p><p>这种格式监控多虚拟主机连接状态：<br />重点启crond服务，仍后通过http://219.32.205.13/nginx/html/ 即可访问。配置过程很简单！</p><p>3、 CACTI模板监控Nginx</p><p>利用Nginx_status状态来画图实现CACTI监控<br />nginx编译时允许http_stub_status_module</p><p># vi /usr/local/nginx/conf/nginx.conf</p><div class="hl-surround"><div class="hl-main">location /nginx_status &#123;<br />&nbsp;&nbsp; &nbsp;stub_status on;<br />&nbsp;&nbsp; &nbsp;access_log off;<br />&nbsp;&nbsp; &nbsp;allow 192.168.1.37;<br />&nbsp;&nbsp; &nbsp;deny all;<br />&#125;</div></div><div class="hl-surround"><div class="hl-main"># kill -HUP `cat /usr/local/nginx/logs/nginx.pid`<br /># wget http://forums.cacti.net/download.php?id=12676<br /># tar xvfz cacti-nginx.tar.gz<br /># cp cacti-nginx/get_nginx_socket_status.pl /data/cacti/scripts/<br /># cp cacti-nginx/get_nginx_clients_status.pl /data/cacti/scripts/<br /># chmod 755 /data/cacti/scripts/get_nginx*</div></div><p>检测插件<br /># /data/cacti/scripts/get_nginx_clients_status.pl http://192.168.1.37/nginx_status</p><p>在cacti管理面板导入</p><div class="hl-surround"><div class="hl-main">cacti_graph_template_nginx_clients_stat.xml<br />cacti_graph_template_nginx_sockets_stat.xml</div></div><p>十六、常见问题与错误处理</p><p>1、 400 bad request错误的原因和解决办法<br />配置nginx.conf相关设置如下.</p><div class="hl-surround"><div class="hl-main">client_header_buffer_size 16k;<br />large_client_header_buffers 4 64k;</div></div><p>根据具体情况调整，一般适当调整值就可以。</p><p>2、 Nginx 502 Bad Gateway错误</p><div class="hl-surround"><div class="hl-main">proxy_next_upstream error timeout invalid_header http_500 http_503;</div></div><p>或者尝试设置:</p><div class="hl-surround"><div class="hl-main">large_client_header_buffers 4 32k;</div></div><p>3、 Nginx出现的413 Request Entity Too Large错误</p><p>这个错误一般在上传文件的时候会出现，</p><p>编辑Nginx主配置文件Nginx.conf，找到http&#123;&#125;段，添加</p><div class="hl-surround"><div class="hl-main">client_max_body_size 10m; //设置多大根据自己的需求作调整.</div></div><p>如果运行php的话这个大小client_max_body_size要和php.ini中的如下值的最大值<br />一致或者稍大，这样就不会因为提交数据大小不一致出现的错误。</p><div class="hl-surround"><div class="hl-main">post_max_size = 10M<br />upload_max_filesize = 2M</div></div><p>4、 解决504 Gateway Time-out(nginx)</p><p>遇到这个问题是在升级discuz论坛的时候遇到的</p><p>一般看来, 这种情况可能是由于nginx默认的fastcgi进程响应的缓冲区太小造成的,<br />这将导致fastcgi进程被挂起, 如果你的fastcgi服务对这个挂起处理的不好, 那么最后就<br />极有可能导致504 Gateway Time-out</p><p>现在的网站, 尤其某些论坛有大量的回复和很多内容的, 一个页面甚至有几百K。</p><p>默认的fastcgi进程响应的缓冲区是8K, 我们可以设置大点</p><p>在nginx.conf里, 加入：</p><div class="hl-surround"><div class="hl-main">fastcgi_buffers 8 128k</div></div><p>这表示设置fastcgi缓冲区为8&times;128k</p><p>当然如果您在进行某一项即时的操作, 可能需要nginx的超时参数调大点，例如设置成60秒：</p><div class="hl-surround"><div class="hl-main">send_timeout 60;</div></div><p>只是调整了这两个参数, 结果就是没有再显示那个超时, 可以说效果不错, 但是也<br />可能是由于其他的原因, 目前关于nginx的资料不是很多, 很多事情都需要长期的经验<br />累计才有结果, 期待您的发现哈!</p><p>5、 如何使用Nginx Proxy</p><p>朋友一台服务器运行tomcat 为8080端口,IP:192.168.1.2:8080,另一台机器<br />IP:192.168.1.8. 朋友想通过访问http://192.168.1.8即可访问tomcat服务.配置如下:</p><p>在192.168.1.8的nginx.conf上配置如下:</p><div class="hl-surround"><div class="hl-main">server &#123;<br />&nbsp;&nbsp; &nbsp;listen 80;<br />&nbsp;&nbsp; &nbsp;server_name java.linuxtone.org<br />&nbsp;&nbsp; &nbsp;location / &#123;<br />&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;proxy_pass http://192.168.1.2:8080;<br />&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;include /usr/local/nginx/conf/proxy.conf;<br />&nbsp;&nbsp; &nbsp;&#125;<br />&#125;</div></div><p>6、 如何关闭Nginx的LOG</p><div class="hl-surround"><div class="hl-main">access_log /dev/null;<br />error_log /dev/null;</div></div><p>十七、相关资源下载</p><p>1. nginx配置示例及脚本下载:<br /># wget http://www.linuxtone.org/lemp/scripts.tar.gz #此脚本范例定期更新.</p><br/>Tags - <a href="http://liuxinxiu.com:80/tags/nginx%25E4%25B8%25AD%25E6%2596%2587%25E6%2589%258B%25E5%2586%258C/" rel="tag">nginx中文手册</a>
]]>
</description>
</item><item>
<link>http://liuxinxiu.com:80/nginx_manual/#blogcomment96</link>
<title><![CDATA[[评论] 【转载】Nginx中文手册（技术指南第二版）]]></title> 
<author>路过的人 &lt;adsf@tom.com&gt;</author>
<category><![CDATA[评论]]></category>
<pubDate>Mon, 04 Jul 2011 13:49:35 +0000</pubDate> 
<guid>http://liuxinxiu.com:80/nginx_manual/#blogcomment96</guid> 
<description>
<![CDATA[ 
	不错。。。看过了
]]>
</description>
</item>
</channel>
</rss>