Nginx常见应用技术指南(Nginx Tips) – 转

发现一篇关于Nginx使用Tips的好文,特转载与此

Nginx 技术指南[NGINX TIPS]

转自:http://bbs.linuxtone.org/thread-1241-1-1.html

Nginx 常见应用技术指南(Nginx Tips)[定期更新]

作者:NetSeek http://www.linuxtone.org(IT运维专家网|集群架构|性能调优)
欢迎转载,转载时请务必以超链接形式标明文章原始出处和作者信息及本声明.
更新时间:[2008-12-4] 第一版:[2008-11-25]

目录:
一. Nginx基础知识
二. Nginx安装配置
三. Nginx Rewrite
四. Nginx Redirect
五. Nginx 目录自动加斜线
六. Nginx 防盗链
七. Nginx expires
八. Nginx 访问控制
九. Nginx Location
十. Nginx 日志处理
十一.   Nginx Cache服务配置
十二.   Nginx 负载均衡
十三.   Nginx 优化
十四.   Nginx 相关参考文档


【前言】
编写此技术指南在于推广普及NGINX在国内的使用,更方便的帮助大家了解和掌握NGINX的一些使用技巧。本指南很多技巧来自于网络在此对网络上愿意分享的朋友们表示感谢和致意!欢迎大家和我一起丰富本技术指南并提出更好的建议!

一.Nginx 基础知识
1.简介
Nginx (“engine x”) 是一个高性能的 HTTP 和 反向代理 服务器,也是一个 IMAP/POP3/SMTP 代理服务器。 Nginx 是由 Igor Sysoev 为俄罗斯访问量第二的 Rambler.ru 站点开发的,它已经在该站点运行超过两年半了。Igor 将源代码以类BSD许可证的形式发布。尽管还是测试版,但是,Nginx 已经因为它的稳定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名了。更多的请见官方wiki: http://wiki.codemongers.com/NginxChs

2.Nginx的优点
nginx做为HTTP服务器,有以下几项基本特性:
1.处理静态文件,索引文件以及自动索引;打开文件描述符缓冲.
2.无缓存的反向代理加速,简单的负载均衡和容错.

3.FastCGI,简单的负载均衡和容错.

4.模块化的结构。包括gzipping, byte ranges, chunked responses, 以及 SSI-filter等filter。如果由FastCGI或其它代理服务器处理单页中存在的多个SSI,则这项处理可以并行运行,而不需要相互等待。

5.支持SSL 和 TLS SNI.
Nginx专为性能优化而开发,性能是其最重要的考量, 实现上非常注重效率 。它支持内核Poll模型,能经受高负载的考验, 有报告表明能支持高达 50,000 个并发连接数。
Nginx具有很高的稳定性。其它HTTP服务器,当遇到访问的峰值,或者有人恶意发起慢速连接时,也很可能会导致服务器物理内存耗尽频繁交换,失去响应,只能重启服务器。例如当前apache一旦上到200个以上进程,web响 应速度就明显非常缓慢了。而Nginx采取了分阶段资源分配技术,使得它的CPU与内存占用率非常低。nginx官方表示保持10,000个没有活动的连 接,它只占2.5M内存,所以类似DOS这样的攻击对nginx来说基本上是毫无用处的。就稳定性而言, nginx比lighthttpd更胜一筹。
Nginx支持热部署。它的启动特别容易, 并且几乎可以做到7*24不间断运行,即使运行数个月也不需要重新启动。你还能够在不间断服务的情况下,对软件版本进行进行升级。
Nginx采用master-slave模型, 能够充分利用SMP的优势,且能够减少工作进程在磁盘I/O的阻塞延迟。当采用select()/poll()调用时,还可以限制每个进程的连接数。
Nginx代码质量非常高,代码很规范, 手法成熟, 模块扩展也很容易。特别值得一提的是强大的Upstream与Filter链。 Upstream为诸如reverse proxy, 与其他服务器通信模块的编写奠定了很好的基础。而Filter链最酷的部分就是各个filter不必等待前一个filter执行完毕。它可以把前一个 filter的输出做为当前filter的输入,这有点像Unix的管线。这意味着,一个模块可以开始压缩从后端服务器发送过来的请求,且可以在模块接收 完后端服务器的整个请求之前把压缩流转向客户端。
Nginx采用了一些os提供的最新特性如对sendfile (Linux 2.2+),accept-filter (FreeBSD 4.1+),TCP_DEFER_ACCEPT (Linux 2.4+) 的支持,从而大大提高了性能。

二. Nginx 安装配置

1.安装pcre

  1. ./configure
  2. make && make install
  3. cd ../

复制代码

3.nginx 编译安装

  1. ./configure –user=www –group=www –prefix=/usr/local/nginx/ –with-http_stub_status_module –with-openssl=/usr/local/openssl
  2. make && make install

复制代码

更详细的模块定制与安装请参照官方wiki.

三. Nginx Rewrite

1.Nginx Rewrite 基本标记(flags)

  1. last – 基本上都用这个Flag。
  2. break – 中止Rewirte,不在继续匹配
  3. redirect – 返回临时重定向的HTTP状态302
  4. permanent – 返回永久重定向的HTTP状态301

复制代码

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

  1. * ~   为区分大小写匹配
  2. * ~* 为不区分大小写匹配
  3. * !~和!~*分别为区分大小写不匹配及不区分大小写不匹配

复制代码

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

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

复制代码


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

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

复制代码

四.Nginx Redirect
将所有linuxtone.org与abc.linuxtone.org域名全部自跳转到http://www.linuxtone.org

  1. server
  2. {
  3. listen 80;
  4. server_name linuxtone.org abc.linuxtone.org;
  5. index index.html index.php;
  6. root /data/www/wwwroot;
  7. if ($http_host !~ “^www\.linxtone\.org$”) {
  8. rewrite ^(.*) http://www.linuxtone.org$1 redirect;
  9. }
  10. ……………………
  11. }

复制代码

五.Nginx 目录自动加斜线:

  1. if (-d $request_filename){
  2. rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
  3. }

复制代码

六.Nginx 防盗链
1.针对不同的文件类型

  1. #Preventing hot linking of images and other file types
  2. location ~* ^.+\.(gif|jpg|png|swf|flv|rar|zip)$ {
  3. valid_referers none blocked server_names *.linuxtone.org http://localhost baidu.com;
  4. if ($invalid_referer) {
  5. rewrite ^/ http://www.linuxtone.org/images/default/logo.gif;
  6. #return 403;
  7. }
  8. }
  9. }

复制代码

2.针对不同的目录

  1. location /img/ {
  2. root /data/www/wwwroot/bbs/img/;
  3. valid_referers none blocked server_names *.linuxtone.org http://localhost baidu.com;
  4. if ($invalid_referer) {
  5. rewrite   ^/   http://www.linuxtone.org/images/default/logo.gif;
  6. #return 403;
  7. }
  8. }

复制代码

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

  1. #Preventing hot linking of images and other file types
  2. location ~* ^.+\.(gif|jpg|png|swf|flv|rar|zip)$ {
  3. valid_referers none blocked server_names *.linuxtone.org http://localhost baidu.com;
  4. if ($invalid_referer) {
  5. rewrite ^/ http://www.linuxtone.org/images/default/logo.gif;
  6. #return 403;
  7. }
  8. }
  9. access_log off;
  10. root /data/www/wwwroot/bbs;
  11. expires 1d;
  12. break;
  13. }

复制代码

七.Nginx expires

1.        根据文件类型expires

  1. # Add expires header for static content
  2. location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ {
  3. if (-f $request_filename) {
  4. root /data/www/wwwroot/bbs;
  5. expires    1d;
  6. break;
  7. }
  8. }

复制代码


2.根据判断某个目录

  1. # serve static files
  2. location ~ ^/(images|javascript|js|css|flash|media|static)/   {
  3. root /data/www/wwwroot/down;
  4. expires 30d;
  5. }

复制代码

八.Nginx 访问控制

1.Nginx 身份证验证

  1. #cd /usr/local/nginx/conf
  2. #mkdir htpasswd
  3. /usr/local/apache2/bin/htpasswd -c /usr/local/nginx/conf/htpasswd/tongji linuxtone #添加用户名为linuxtone
  4. New password: (此处输入你的密码)
  5. Re-type new password: (再次输入你的密码)
  6. Adding password for user
  7. http://count.linuxtone.org/tongji/data/index.html(目录存在/data/www/wwwroot/tongji/data/目录下)
  8. 将下段配置放到虚拟主机目录,当访问http://count.linuxtone/tongji/即提示要密验证:
  9. location ~ ^/(tongji)/   {
  10. root /data/www/wwwroot/count;
  11. auth_basic              “LT-COUNT-TongJi”;
  12. auth_basic_user_file   /usr/local/nginx/conf/htpasswd/tongji;
  13. }

复制代码


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

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

  1. location ~* \.(txt|doc)$ {
  2. if (-f $request_filename) {
  3. root /data/www/wwwroot/linuxtone/test;
  4. break;
  5. }
  6. }

复制代码

方法2:

  1. location ~* \.(txt|doc)${
  2. root /data/www/wwwroot/linuxtone/test;
  3. deny all;
  4. }

复制代码

禁止访问某个目录

  1. location ~ ^/(WEB-INF)/ {
  2. deny all;
  3. }

复制代码


3.使用ngx_http_access_module限制ip访问

  1. location / {
  2. deny 192.168.1.1;
  3. allow 192.168.1.0/24;
  4. allow 10.1.1.0/16;
  5. deny all;
  6. }

复制代码

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


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

  1. limit_zone one   $binary_remote_addr   10m;
  2. server
  3. {
  4. listen    80;
  5. server_name   down.linuxotne.org;
  6. index index.html index.htm index.php;
  7. root /data/www/wwwroot/down;
  8. #Zone limit
  9. location / {
  10. limit_conn one   1;
  11. limit_rate   20k;
  12. }
  13. ……….
  14. }

复制代码


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

  1. location   /   {
  2. autoindex   on;
  3. }

复制代码

九.Nginx Location

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

  1. location [=|~|~*|^~] /uri/ { … }
  2. * ~   为区分大小写匹配
  3. * ~* 为不区分大小写匹配
  4. * !~和!~*分别为区分大小写不匹配及不区分大小写不匹配

复制代码

示例1:

  1. location = / {
  2. # matches the query / only.
  3. # 只匹配 / 查询。
  4. }

复制代码

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

  1. location ^~ /images/ {
  2. # matches any query beginning with /images/ and halts searching,
  3. # so regular expressions will not be checked.

复制代码

# 匹配任何已 /images/ 开头的任何查询并且停止搜索。任何正则表达式将不会被测试。
示例3:

  1. location ~* \.(gif|jpg|jpeg)$ {
  2. # matches any request ending in gif, jpg, or jpeg. However, all
  3. # requests to the /images/ directory will be handled by
  4. }

复制代码

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

十.Nginx 日志处理
1.Nginx 日志切割

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

复制代码

[root@count ~]# cat /usr/local/sbin/logcron.sh

  1. #!/bin/bash
  2. log_dir=”/data/logs”
  3. time=`date +%Y%m%d`
  4. /bin/mv   ${log_dir}/access_linuxtone.org.log ${log_dir}/access_count.linuxtone.org.$time.log
  5. kill -USR1 `cat   /var/run/nginx.pid`

复制代码

更多的日志分析与处理就关注(同时欢迎你参加讨论):http://bbs.linuxtone.org/forum-8-1.html


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

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

  1. location ~ .*\.(js|jpg|JPG|jpeg|JPEG|css|bmp|gif|GIF)$
  2. {
  3. access_log off;
  4. }

复制代码

十一.Nginx Cache服务配置
如果需要将文件缓存到本地,则需要增加如下几个子参数:

  1. proxy_store on;
  2. proxy_store_access user:rw group:rw all:rw;
  3. proxy_temp_path 缓存目录;

复制代码

其中,
proxy_store on用来启用缓存到本地的功能,
proxy_temp_path用来指定缓存在哪个目录下,如:proxy_temp_path html;

在经过上一步配置之后,虽然文件被缓存到了本地磁盘上,但每次请求仍会向远端拉取文件,为了避免去远端拉取文件,必须修改proxy_pass:

  1. if ( !-e $request_filename) {
  2. proxy_pass   http://mysvr;
  3. }

复制代码

即改成有条件地去执行proxy_pass,这个条件就是当请求的文件在本地的proxy_temp_path指定的目录下不存在时,再向后端拉取。

十二.Nginx 负载均衡
1. Nginx 基础知识
nginx的upstream目前支持4种方式的分配

1)、轮询(默认)

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

2)、weight

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

2)、ip_hash

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

3)、fair(第三方)

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

4)、url_hash(第三方)

3.Nginx 负载均衡

实例1

  1. upstream bbs.linuxtone.org {#定义负载均衡设备的Ip及设备状态
  2. server 127.0.0.1:9090 down;
  3. server 127.0.0.1:8080 weight=2;
  4. server 127.0.0.1:6060;
  5. server 127.0.0.1:7070 backup;
  6. }

复制代码

在需要使用负载均衡的server中增加

  1. proxy_pass http://bbs.linuxtone.org/;

复制代码

每个设备的状态设置为:

  1. 1.down 表示单前的server暂时不参与负载
  2. 2.weight 默认为1.weight越大,负载的权重就越大。
  3. 3.max_fails :允许请求失败的次数默认为1.当超过最大次数时,返回proxy_next_upstream 模块定义的错误
  4. 4.fail_timeout:max_fails次失败后,暂停的时间。
  5. 5.backup: 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。

复制代码

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

client_body_in_file_only 设置为On 可以讲client post过来的数据记录到文件中用来做debug
client_body_temp_path 设置记录文件的目录 可以设置最多3层目录
location 对URL进行匹配.可以进行重定向或者进行新的代理 负载均衡

4.Nginx 负载均衡实例
2
按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,后端服务器为缓存时比较有效,也可以用作提高Squid缓存命中率.

简单的负载均等实例:
#vi nginx.conf   //nginx主配置文件核心配置

  1. ……….
  2. #loadblance my.linuxtone.org
  3. upstream   my.linuxtone.org   {
  4. ip_hash;
  5. server 127.0.0.1:8080;
  6. server 192.168.169.136:8080;
  7. server 219.101.75.138:8080;
  8. server 192.168.169.117;
  9. server 192.168.169.118;
  10. server 192.168.169.119;
  11. }
  12. …………..
  13. include       vhosts/linuxtone_lb.conf;
  14. ………
  15. #vi proxy.conf
  16. proxy_redirect off;
  17. proxy_set_header Host $host;
  18. proxy_set_header X-Real-IP $remote_addr;
  19. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  20. client_max_body_size 50m;
  21. client_body_buffer_size 256k;
  22. proxy_connect_timeout 30;
  23. proxy_send_timeout 30;
  24. proxy_read_timeout 60;
  25. proxy_buffer_size 4k;
  26. proxy_buffers 4 32k;
  27. proxy_busy_buffers_size 64k;
  28. proxy_temp_file_write_size 64k;
  29. proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;
  30. proxy_max_temp_file_size 128m;
  31. proxy_store on;
  32. proxy_store_access user:rw   group:rw   all:r;
  33. #nginx cache
  34. client_body_temp_path   /data/nginx_cache/client_body 1 2;
  35. proxy_temp_path /data/nginx_cache/proxy_temp 1 2;

复制代码

#vi linuxtone_lb.conf

  1. server
  2. {
  3. listen   80;
  4. server_name my.linuxtone.org;
  5. index index.php;
  6. root /data/www/wwwroot/mylinuxtone;
  7. if (-f $request_filename) {
  8. break;
  9. }
  10. if (-f $request_filename/index.php) {
  11. rewrite (.*) $1/index.php break;
  12. }
  13. error_page 403 http://my.linuxtone.org/member.php?m=user&a=login;
  14. location / {
  15. if ( !-e $request_filename) {
  16. proxy_pass http://my.linuxtone.org;
  17. break;
  18. }
  19. include /usr/local/nginx/conf/proxy.conf;
  20. }
  21. }

复制代码

十三.Nginx 优化

1.减小nginx编译后的文件大小 (Reduce file size of nginx)

默认的nginx编译选项里居然是用debug模式(-g)的(debug模式会插入很多跟踪和ASSERT之类),编译以后一个nginx有好几兆。去掉nginx的debug模式编译,编译以后只有几百K
在 auto/cc/gcc,最后几行有:
# debug
CFLAGS=”$CFLAGS -g”
注释掉或删掉这几行,重新编译即可。


2.修改Nginx的header伪装服务器

  1. # cd nginx-0.6.31
  2. # vi src/core/nginx.h
  3. #ifndef _NGINX_H_INCLUDED_
  4. #define _NGINX_H_INCLUDED_
  5. #define NGINX_VERSION    “1.3″
  6. #define NGINX_VER       “LTWS/” NGINX_VERSION
  7. #define NGINX_VAR       “NGINX”
  8. #define NGX_OLDPID_EXT     “.oldbin”
  9. #endif /* _NGINX_H_INCLUDED_ */
  10. # curl -I my.linuxtone.org
  11. HTTP/1.1 200 OK
  12. Server: LTWS/1.3
  13. Date: Mon, 24 Nov 2008 02:42:51 GMT
  14. Content-Type: text/html; charset=gbk
  15. Transfer-Encoding: chunked
  16. Connection: keep-alive

复制代码

十四.Nginx 相关参考文档

1.Nginx Debug技巧

/usr/local/nginx/sbin/nginx –t 调试配置是否有语法错误。

Popularity: 6% [?]

Related

Comments

Comments are closed.