nginx 优化

a. nginx安装

   参考: https://www.cnblogs.com/hcl1991/p/6270964.html

b. 修改nginx.conf 配置文件

#user  nobody;          # 运行用户
worker_processes  2;    # 通常配置成cpu的总核数, 或者其2倍, 性能会更好, 可以减少进程间切换带来的消耗。

pid  /var/run/nginx/nginx.pid;    # 进程id的存储位置
worker_rlimit_nofile 65535;     # 一个nginx进程打开的最多的文件数目,设置为最大65535。

# 工作模式及连接数上限
events {
    use epoll;                  # nginx工作模式,epoll是linux平台下的高效模式
    worker_connections  65535;    # 单个后台worker process进程的最大并发链接数
}

# 设定http服务器
http {
    
    include  mime.types;                        # 主模块指令, 实现对配置文件所包含的文件设定
    default_type  application/octet-stream;     # http核心模块指令,这里默认类型为二进制流,浏览器下载文件,避免直接打开
    
    charset  utf-8;
   
    server_names_hash_bucket_size  128;     # 服务器名字的hash表大小
    proxy_headers_hash_max_size 51200;   # 设置头部哈希表的最大值,不能小于你后端服务器设置的头部总数
    proxy_headers_hash_bucket_size 6400; # 设置头部哈希表大小
    client_header_buffer_size  32k;      # 用于指定来自客户端请求头headerbuffer大小
    client_header_timeout 3m;            # 设置客户端请求读取超时时间,如果超时,nginx将返回“request time out (408)”错误。
    client_body_timeout 3m;              # 设置客户端请求主体读取超时时间,默认值为60.如果超时,nginx将返回“Request time out(408)”
    client_max_body_size 365m;           # 上传文件大小
    large_client_header_buffers 4 32k;     # 指定客户端请求中较大的消息头的缓存最大数量和大小,这里是4个32KB
    
    autoindex  on;         # 开启目录列表访问,合适下载服务器,默认关闭。
    sendfile  on;        # 开启高效文件传输模式,将tcp_nopush和tcp_nodely两个指令设置为on,用于防止网络阻塞。
    #tcp_nopush  on;    # 防止网络阻塞
    #tcp_nodely  on;    # 防止网络阻塞

    keepalive_timeout  65;    # 用于设置客户端连接保持活动的超时时间,在超过这个时间之后服务器会关闭该链接。
    server_tokens   off;        # 修改或隐藏Nginx的版本号


    # FastCGI相关参数是为了改善网站的性能:减少资源占用,提高访问速度。下面参数看字面意思都能理解。
    fastcgi_connect_timeout 300;  # 指定连接到后端fastCGI的超时时间
    fastcgi_send_timeout 300;     # 向fastCGI请求的超时时间,这个值是指已经完成两次握手后向fastCGI传送的超时时间
    fastcgi_read_timeout 300;     # 接收fastCGI应答的超时时间,这个值已经完成两次握手后接收fastCGI应答的超时时间
    fastcgi_buffer_size 64k;      # 指定读取fastCGI应答第一部分需要用多大的缓冲区,一般第一部分应答不会超过1k,一般设置为64k
    fastcgi_buffers 4 64k;        # 指定本地需要用多少和多大的缓冲区来缓冲fastCGI的应答
    fastcgi_busy_buffers_size 128k;     # 默认值是fastcgi_buffers的两倍
    fastcgi_temp_file_write_size 128k;  # 在写入fastcgi_temp_path是用多大的数据块,默认值是fastcgi_buffers两倍
    
    
    client_body_buffer_size 128k; # 客户端请求主体缓存区大小
    proxy_connect_timeout 120;    # 与后端服务器连接的超时时间
    proxy_send_timeout  120;      # 后端服务器的数据回传时间120s,120s内未传回,nginx将断开连接
    proxy_read_timeout  120;      # nginx从代理的后端服务器获取信息的时间120s
    proxy_buffer_size 64k;        # 缓冲区大小默认等于proxy_buffers设置的大小
    proxy_buffers 4 32k;          # 设置缓冲区的数量和大小
    proxy_busy_buffers_size 64k;     # 设置系统很忙时可以使用的proxy_buffers的大小,官方推荐位proxy_buffersX2
    proxy_temp_file_write_size 64k;  # 指定proxy缓存临时文件的大小

       
    # gzip模块设置
    gzip  on;  # 开启gzip压缩
    gzip_min_length 1k;     # 允许压缩的最小字节数,页面字节数从header头的content-length中获取,默认值是0
    gzip_buffers 4 16k;     # 申请4个单位为16k的内存作为压缩结果流缓存,默认值是申请与原始数据大小相同的内存空间来存储gzip压缩结果
    gzip_http_version 1.1;  # 压缩版本(默认1.1,前端如果是squid2.5请使用1.0)
    gzip_comp_level  2;     # 压缩等级,1~9中设置,1压缩比最小,速度最快,9压缩比最大,速度最慢,消耗CPU
    gzip_vary  on;          # 选项可让前端的缓存服务器缓存经过gzip压缩的页面,例如,用squid缓存经过nginx压缩的数据。
    gzip_types text/plain application/x-javascript text/css application/xml;  # 压缩类型,默认就已经包含text/html
    #limit_zone crawler $binary_remote_addr 10m;  # 开启限制IP连接数的时候需要使用


    # nginx日志的默认输出格式
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" '
                      '$request_time';  #加入request_time, 统计传输时间

    log_format access '$http_x_forwarded_for - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent"' ;

    # 自定义日志输出位置
    access_log /data/logs/nginx/access.log main;
    error_log /data/logs/nginx/error.log;    

    #简单的节点配置(当这些API都用到同一个Backend时,代码中的proxy_set_header传递的host就起到了关键性作用)
    upstream online {
       #ip_hash;  # 每个请求按访问ip的hash结果分配,这样来自同一个ip的访客固定访问一个后端服务器,有效解决动态网页存在的session共享问题
       server 127.0.0.1:8080 weight=1;
       #server 127.0.0.1:8081 weight=1;
    }
    
    
    # 不同路径映射到不同项目上
    server {
       listen 80;
       server_name www.test.com;

       # jenkins访问路径
       location /jenkins {
           proxy_pass      http://127.0.0.1:8090/jenkins;
       }
       
       # nexus私服访问路径
       location /nexus {
           proxy_pass      http://127.0.0.1:8088/nexus;
       }

    }
    
    
    # online域名映射
    server {
       listen 80;
       server_name www.test.com;
       
       # 项目名访问
        location /dofun-console {
            proxy_set_header   Host             $host;
            proxy_set_header   X-Real-IP        $remote_addr;
            #Web服务器可以通过X-Forwarded-For获取用户真实IP
            proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
            #以上三行,目的是将代理服务器收到的用户的信息传到真实服务器上

            proxy_pass http://127.0.0.1:8080/dofun-console;

            #proxy_redirect 不加 出现js.css访问404错误, 这里意思是 
            #http://$hots(127.0.0.1):$server_port(80) 替换 http://127.0.0.1:8080 这样js,css就能访问了
            proxy_redirect http://127.0.0.1:8080 http://$host:$server_port;
        }


    }
    

    # goaccess 日志分析
    server {
        listen       83;
        server_name  127.0.0.1;

        location / {
            root   html;
            index  report.html;
        }
    }


    # 81端口监控用于图片下载  
    server {
       listen 82;
       server_name  localhost;
       root   /;      
 
       location / {
           #如果是图片就下载文件
           if ($request_filename ~* ^.*?.(txt|doc|pdf|rar|gz|zip|docx|exe|xlsx|ppt|pptx)$){
               add_header Content-Disposition: 'attachment;';
           }
       }
    }
}

c. 命令行分析nginx日志

# nginx 默认日志格式
log_format  access  '$remote_addr - $remote_user [$time_local] "$request" '
                             '$status $body_bytes_sent "$http_referer" '
                             '"$http_user_agent" "$http_x_forwarded_for"';  

$remote_addr    客户端地址 211.28.65.253
$remote_user     客户端用户名称 --
$time_local     访问时间和时区 18/Jul/2012:17:00:01 +0800
$request       请求的URI和HTTP协议 "GET /article-10000.html HTTP/1.1"
$http_host      请求地址,即浏览器中你输入的地址(IP或域名) www.it300.com 192.168.100.100
$status        HTTP请求状态 200
$upstream_status   upstream状态 200
$body_bytes_sent   发送给客户端文件内容大小 1547
$http_referer url  跳转来源 https://www.baidu.com/
$http_user_agent   用户终端浏览器信息 "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; SV1; GTB7.0; .NET4.0C;
$ssl_protocol      SSL协议版本 TLSv1
$ssl_cipher        交换数据中的算法 RC4-SHA
$upstream_addr     后台upstream的地址,即真正提供服务的主机地址 10.10.10.100:80
$request_time      整个请求的总时间 0.205
$upstream_response_time 请求过程中,upstream响应时间 0.002

# 统计独立IP访问量
    awk '{print $1}' access.log | sort -n | uniq | wc -l

# 查看某一时间段IP访问量(4-5点)
    grep "09/May/2019:0[4-5]" access.log | awk '{print $1}' | sort | uniq -c| sort -nr | wc -l

# 查看访问最频繁的前100 IP
    awk '{print $1}' access.log | sort -n |uniq -c | sort -rn | head -n 100

# 查看访问100次以上的IP
    awk '{print $1}' access.log | sort -n |uniq -c |awk '{if($1 >100) print $0}'|sort -rn

# 查询某个IP的详细访问情况,按访问频率排序
    grep '127.0.01' access.log |awk '{print $7}'|sort |uniq -c |sort -rn |head -n 100


# 统计每秒的请求数,top100的时间点(精确到秒)
    awk '{print $4}' access.log |cut -c 14-21|sort|uniq -c|sort -nr|head -n 100

#  统计每分钟的请求数,top100的时间点(精确到分钟)  
    awk '{print $4}' access.log |cut -c 14-18|sort|uniq -c|sort -nr|head -n 100         

# 统计每小时的请求数,top100的时间点(精确到小时)
    awk '{print $4}' access.log |cut -c 14-15|sort|uniq -c|sort -nr|head -n 100

在nginx log中最后一个字段加入$request_time
# 列出传输时间超过 3 秒的页面,显示前20条
    cat access.log|awk '($NF > 3){print $7}'|sort -n|uniq -c|sort -nr|head -20

d. nginx 日志分析工具goaccess

   参考: https://www.cnblogs.com/hcl1991/p/10634711.html

参考:

  百万并发下的nginx优化之道: https://baijiahao.baidu.com/s?id=1615824183355202778&wfr=spider&for=pc

  nginx log日志统计分析常用命令: https://www.cnblogs.com/gouge/p/7089939.html

  nginx location路径匹配问题: https://betakoli.iteye.com/blog/2431428

  nignx 的log_format用法梳理: https://www.cnblogs.com/kevingrace/p/5893499.html

  nginx 错误日志与优化专题: https://www.cnblogs.com/tinywan/p/6777592.html

  阿里云日志服务nginx: https://yq.aliyun.com/articles/365307

       nginx 响应超时 : https://blog.csdn.net/u014218983/article/details/81217032#%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95

原文地址:https://www.cnblogs.com/hcl1991/p/10838912.html