zoukankan      html  css  js  c++  java
  • Nginx 常见应用技术指南

    .Nginx 日志切割
    #contab -e
    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.利用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服务配置
    如果需要将文件缓存到本地,则需要增加如下几个子参数:

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

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

    复制代码

    即改成有条件地去执行proxy_pass,这个条件就是当请求的文件在本地的proxy_temp_path指定的目录下不存在时,再向后端拉取。
    更多更高级的应用可以研究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

    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中增加
    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主配置文件核心配置

    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

    1. CFLAGS=”$CFLAGS -g”

    复制代码

    注释掉或删掉这几行,重新编译即可。
    2.        修改Nginx的header伪装服务器
    1)        修改nginx.h

    1. #vi nginx-0.7.30/src/core/nginx.h
    2. #define NGINX_VERSION      "1.8"
    3. #define NGINX_VER          "LTWS/" NGINX_VERSION
    4. #define NGINX_VAR          "NGINX"
    5. #define NGX_OLDPID_EXT     ".oldbin"

    复制代码

    2) 修改nginx_http_header_filter_module
    #vi nginx-0.7.30/src/http/ngx_http_header_filter_module.c
    将如下

    1. static char ngx_http_server_string[] = "Server: nginx" CRLF;

    复制代码

    修改为

    1. static char ngx_http_server_string[] = "Server: LTWS" CRLF;

    复制代码

    a)        修改nginx_http_header_filter_module
    #vi nginx-0.7.30/src/http/ngx_http_special_response.c
    将如下:

    1. static u_char ngx_http_error_full_tail[] =
    2. "<hr><center>" NGINX_VER "</center>" CRLF
    3. "</body>" CRLF
    4. "</html>" CRLF
    5. ;

    复制代码

    1. static u_char ngx_http_error_tail[] =
    2. "<hr><center>nginx</center>" CRLF
    3. "</body>" CRLF
    4. "</html>" CRLF
    5. ;

    复制代码

    修改为:

    1. static u_char ngx_http_error_full_tail[] =
    2. "<center> "NGINX_VER" </center>" CRLF
    3. "<hr><center>http://www.linuxtone.org</center>" CRLF
    4. "</body>" CRLF
    5. "</html>" CRLF
    6. ;
    7. static u_char ngx_http_error_tail[] =
    8. "<hr><center>LTWS</center>" CRLF
    9. "</body>" CRLF
    10. "</html>" CRLF
    11. ;

    复制代码

    修改后重新编译一下环境,
    404错误的时候显示效果图(如果没有指定错误页的话):

    利用curl命令查看服务器header

    下载 (3.02 KB)

    2009-2-2 00:20

    3.为特定的CPU指定CPU类型编译优化.
    默认nginx使用的GCC编译参数是-O
    需要更加优化可以使用以下两个参数
    --with-cc-opt='-O3'
    --with-cpu-opt=opteron
    使得编译针对特定CPU以及增加GCC的优化.
    此方法仅对性能有所改善并不会有很大的性能提升,供朋友们参考.
    CPUD类型确定: # cat /proc/cpuinfo | grep "model name"
    编译优化参数参考:http://en.gentoo-wiki.com/wiki/Safe_Cflags

    4.Tcmalloc优化Nginx 性能

    1. # wget http://download.savannah.gnu.org/releases/libunwind/libunwind-0.99-alpha.tar.gz
    2. # tar zxvf libunwind-0.99-alpha.tar.gz
    3. # cd libunwind-0.99-alpha/
    4. # CFLAGS=-fPIC ./configure
    5. # make CFLAGS=-fPIC
    6. # make CFLAGS=-fPIC install
    7. # wget http://google-perftools.googlecode.com/files/google-perftools-0.98.tar.gz
    8. # tar zxvf google-perftools-0.98.tar.gz
    9. # cd google-perftools-0.98/
    10. # ./configure
    11. # make && make install
    12. # echo "/usr/local/lib" > /etc/ld.so.conf.d/usr_local_lib.conf
    13. # ldconfig
    14. # lsof -n | grep tcmalloc

    复制代码

    编译nginx 加载google_perftools_module:
    ./configure --with-google_perftools_module
    在主配置文件加入nginx.conf 添加:
    google_perftools_profiles /path/to/profile;
    5.内核参数优化
    # vi /etc/sysctl.conf   #在末尾增加以下内容:

    1. net.ipv4.tcp_fin_timeout = 30
    2. net.ipv4.tcp_keepalive_time = 300
    3. net.ipv4.tcp_syncookies = 1
    4. net.ipv4.tcp_tw_reuse = 1
    5. net.ipv4.tcp_tw_recycle = 1
    6. net.ipv4.ip_local_port_range = 5000 65000

    复制代码

    #使配置立即生效
    /sbin/sysctl -p
    十四、如何构建高性的LEMP
    请参见: http://www.linuxtone.org/lemp/lemp.pdf
    1、提供完整的配置脚本下载:http://www.linuxtone.org/lemp/scripts.tar.gz
    2、提供NGINX常见配置范例含(虚拟主机,防盗链,Rewrite,访问控制,负载均衡
    Discuz相关程序静态化及等等),你只要稍稍修改即可线上应用。 3、将原版的xcache替换成EA,并提供相关简单调优脚本及配置文件。
    更多的及更新资料请关注: http://www.linuxtone.org
    十五、Nginx监控
    1、        RRDTOOL+Perl脚本画图监控
    先安装好rrdtool ,关于rrdtool本文不作介绍,具体安装请参照linuxtone监控版块.
    #cd /usr/local/sbnin
    #wget http://blog.kovyrin.net/files/mrtg/rrd_nginx.pl.txt
    #mv rrd_nginx.pl.txt rrd_nginx.pl
    #chmod a+x rrd_nginx.pl
    #vi rrd_nginx.pl   //配置脚本文件设置好路径
    #!/usr/bin/perl
    use RRDs;
    use LWP::UserAgent;
    # define location of rrdtool databases
    my $rrd = '/data/www/wwwroot/nginx/rrd';
    # define location of images
    my $img = '/data/www/wwwroot/nginx/html';
    # define your nginx stats URL
    my $URL = "http://219.232.244.13/nginx_status";
    …………
    【注】根据自己具体的状况修改相应的路径.
    #crontab –e //加入如下
    * * * * * /usr/local/sbin/rrd_nginx.pl
    重启crond后,通过配置nginx虚拟主机指到/data/www/wwwroot/nginx/html目录,通过crond自动执行perl脚本会生成很多图片.
    http://xxx/connections-day.png即可看到服务器状态图。
    2、        官方Nginx-rrd 监控服务(多虚拟主机)(推荐)
    网址:http://www.nginx.eu/nginx-rrd.html
    此解决方案其实是基于上述监控方案的一个改进和增强,同样先安装好rrdtool这个画图工具和相应的perl模块再做如下操作:
    # yum install perl-HTML*
    先建立好生成的库存和图片存放录

    1. #mkdir -p /data/www/wwwroot/nginx/{rrd,html}
    2. #cd /usr/local/sbin
    3. #wget http://www.nginx.eu/nginx-rrd/nginx-rrd-0.1.4.tgz
    4. #tar zxvf nginx-rrd-0.1.4.tgz
    5. #cd nginx-rrd-0.1.4
    6. #cd etc/
    7. #cp nginx-rrd.conf /etc
    8. #cd etc/cron.d
    9. #cp nginx-rrd.cron /etc/cron.d
    10. #cd /usr/local/src/nginx-rrd-0.1.4/html
    11. # cp index.php /data/www/wwwroot/nginx/html/
    12. #cd /usr/local/src/nginx-rrd-0.1.4/usr/sbin
    13. #cp * /usr/sbin/

    复制代码

    #vi /etc/nginx-rrd.conf

    1. #####################################################
    2. #
    3. # dir where rrd databases are stored
    4. RRD_DIR="/data/www/wwwroot/nginx/rrd";
    5. # dir where png images are presented
    6. WWW_DIR="/data/www/wwwroot/nginx/html";
    7. # process nice level
    8. NICE_LEVEL="-19";
    9. # bin dir
    10. BIN_DIR="/usr/sbin";
    11. # servers to test
    12. # server_utl;server_name
    13. SERVERS_URL="http://219.32.205.13/nginx_status;219.32.205.13  http://www.linuxtone.org/nginx_status;www.linuxtone.org""

    复制代码

    //根据你的具体情况做调整.
    SEVERS_URL 格式 http://domain1/nginx_status;domain1 http://domain2/nginx_status;domain2
    这种格式监控多虚拟主机连接状态:
    重点启crond服务,仍后通过http://219.32.205.13/nginx/html/ 即可访问。配置过程很简单!
    3、        CACTI模板监控Nginx
    利用Nginx_status状态来画图实现CACTI监控
    nginx编译时允许http_stub_status_module
    # vi /usr/local/nginx/conf/nginx.conf

    1. location /nginx_status {
    2. stub_status on;
    3. access_log off;
    4. allow 192.168.1.37;
    5. deny all;
    6. }

    复制代码

    1. # kill -HUP `cat /usr/local/nginx/logs/nginx.pid`
    2. # wget http://forums.cacti.net/download.php?id=12676
    3. # tar xvfz cacti-nginx.tar.gz
    4. # cp cacti-nginx/get_nginx_socket_status.pl /data/cacti/scripts/
    5. # cp cacti-nginx/get_nginx_clients_status.pl /data/cacti/scripts/
    6. # chmod 755 /data/cacti/scripts/get_nginx*

    复制代码

    检测插件

    1. # /data/cacti/scripts/get_nginx_clients_status.pl http://192.168.1.37/nginx_status

    复制代码

    在cacti管理面板导入
    cacti_graph_template_nginx_clients_stat.xml
    cacti_graph_template_nginx_sockets_stat.xml
    十六、常见问题与错误处理
    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上配置如下:

    1. server {
    2. listen 80;
    3. server_name java.linuxtone.org
    4. location / {
    5. proxy_pass http://192.168.1.2:8080;
    6. include /usr/local/nginx/conf/proxy.conf;
    7. }
    8. }

    复制代码

    6、如何关闭Nginx的LOG
    access_log /dev/null; error_log /dev/null;

  • 相关阅读:
    微信小程序 | 小程序的转发问题
    开发辅助 | 前端开发工程师必懂的 UI 知识
    微信小程序 | canvas绘图
    服务端 | Linux 学习总结 (一)
    移动端适配 | 适配方案总结
    开发工具 | 利用 deployd 搭建个人博客
    1.10 组织好代码文件,要有“用户思维”
    1.9 组织好代码段,让人对它“一见钟情”
    《计算机是怎样跑起来的》读书笔记(1)
    实用网站收藏
  • 原文地址:https://www.cnblogs.com/hsapphire/p/1707108.html
Copyright © 2011-2022 走看看