Nginx基础

Nginx

基础篇

Nginx的基本情况

  • Nginx作为新一代的HTTP服务,解决了c10k问题,同时还可以作为反向代理、IMAP、POP3和SMTP程序
  • Nginx的优点:I/O多路复用,节省系统资源。epoll
  • 关于epoll:其为Nginx中实现I/O多路复用的方法,经过select和poll的演化,epoll当前的版本可以做到线程的安全性,并在实际使用中告知具体哪个sock有数据。具体的特点为:异步非阻塞

Nginx的部署

YUM

配置yum源如下

[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1

编译安装及参数

  • configure arguments 配置参数
  • --prefix=/etc/nginx 配置文件路径
  • --sbin-path=/usr/sbin/nginx 程序文件
  • --modules-path=/usr/lib64/nginx/modules
  • --conf-path=/etc/nginx/nginx.conf
  • --error--log-path=/var/log/nginx/error.log
  • --http-log-path=/var/log/nginx/access.log
  • --pid-path=/var/run/nginx.pid
  • --lock-path=/var/run/nginx.lock
  • --http-proxy-temp-path=/var/cache/nginx/proxy_temp
  • --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp
  • --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp
  • --http-scgi-temp-path=/var/cache/nginx/scgi_temp
  • --user=nginx
  • --group=nginx
  • --with-compat
  • --with-file-aio
  • --with-threads
  • --with-http_addition_module
  • --with-http_auth_request_module
  • --with-http_dav_module
  • --with-http_flv_module
  • --with-http_gunzip_module
  • --with-http_gzip_static_module
  • --with-http_mp4_module
  • --with-http_mp4_module
  • --with-http_random_index_module
  • --with-http_realip_module
  • --with-http_secure_link_moodule
  • --with-http_slice_link_module
  • --with-http_ssl_module
  • --with-http_stub_status_module
  • --with-http_sub_module
  • --with-http_v2_module
  • --with-mail
  • --with-mail_ssl_module
  • --with-stream
  • --with-stream_realip_module
  • --with-stream_ssl_module
  • --with-stream_ssl_preread_module
  • --with-cc-opt='-O2 -g -pipr -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --parram=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC'
  • --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pir' 1l

与Nginx相关的全部文件

  • /etc/logrotate.d/nginx 日志轮转
  • /etc/nginx 配置文件总目录
  • /etc/nginx/conf.d 自配置文件文件夹
  • /etc/nginx/conf.d/default.conf 默认的网站配置文件
  • /etc/nginx/fastcgi_params
  • /etc/nginx/scgi_params
  • /etc/nginx/uwsgi_params
  • /etc/nginx/koi-utf 字符集,文件编码
  • /etc/nginx/win-utf
  • /etc/nginx/koi-win
  • /etc/nginx/mime.types 关联程序,如网站的文件类型和相关的处理程序
  • /etc/nginx/modules 模块文件夹,第三方模块等
  • /etc/nginx/nginx.conf 主配置文件
  • /usr/lib/systemcd/system/nginx.service.systemctl 服务脚本
  • /usr/sbin/nginx 主程序
  • /usr/share/doc/nginx-1.12.1 文档
  • /usr/share/man/man8/nginx.8.gz
  • /usr/share/nginx/html/index.html默认主页
  • /var/cache/nginx nginx缓存文件
  • /var/log/nginx/ 存放nginx日志的目录

Nginx的基本配置

主配置文件内容详解

user nginx;
worker_processes 1; 
#启动的worker进程的数量(CPU数量一致或auto)
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events{
    use epoll;  
    #事件驱动模型epoll
    worker_connections 1024; 
    #每个worker进程允许处理的最大连接数,通常要改大
}
http{
    include /etc/nginx/mime.types;
    #文档和长须的关联记录
    default_type application/octet-stream;
    #字节流处理方式
    log_format main '$remote_addr - $remote_user [$time_local] "$request"'
    '$status $body_bytes_sent "$http_referer"'
    '"$http_user_agent" "$http_x_forwarded_for"';
    #日志格式
    access_log /var/log/nginx/access.log main;
    sendfile on;
    #优化参数,高效传输文件的模式
    #tcp_nopush on; 
    #TCP停止数据包推送,等积累到最大的时候一起推送到Client
    keepalive_timeout 65;
    #长连接时间
    #gzip on;
    #压缩
    include /etc/nginx/conf.d/*.conf;
    #包含自配置目录
}

虚拟主机的配置文件/etc/nginx/conf.d/default.conf

server{
    listen 80;
    server_name localhost;
    #charset koi8-r;
    #access_log /var/log/nginx/host.access.log main;
    location / {
        root /usr/share/nginx/html;
        index index.html index.html;
    }
    #error_page 404 /404.html;
    #redirect server error pages to the static page /50x.html
    error_page 500 502 503 504 /50x.html;
    location = /50.html {
        root /usr/share/nginx/html;
    }
    #proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #location ~ \.php$ {
        #proxy_pass http://127.0.0.1;
    }
    #pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #location ~ \.php${
        #root html;
        #fastcgi_pass 127.0.0.1:9000;
        #fastcgi_index index.php;
        #fastcgi_param SCRIPT_FILENAME /scipts$fastcgi_script_name;
        #include fastcgi_params;
    }
    #deny access to .htacess files,if Apaches's document root
    #concurs with nginx's one
    #location ~ /\.ht{
        #deny all;
    }
}

新建一个简单的虚拟主机/etc/nginx/conf.d/new.conf

server{
    listen 80;
    server_name new.com;
    location / {
        root /new;
        index index.html index.htm;
    }
}
  • 使用时要配置本地解析

日志配置

简介

Nginx 中有非常灵活的日志记录模式,每个级别的配置可以有各自独立的访问日志。若要使用日志系统需要加载日志模块 ngx_http_log_module(默认开启)

常见变量意义

log_format
#日志格式
access_log
#访问日志
error_log
#错误日志
open_log_file_cache
#日志缓存
  • 关于日志缓存的配置
open_log_file_cache max=N[inactive=time] [min_uses=N] [valid=time] | off
#该指令默认是禁止的
open_log_file_cache off;
#其中参数的描述符说明如下
#max:缓存中最大的文件的描述符数量
#inactive:设置一个事件,如果在设置的事件内没有使用此文件描述符,则自动删除此描述符。
#min_uses:在参数inactive指定的时间范围内,若文件日志超过被使用的次数,则将该日志文件的描述符记入缓存。
#valid:设置多长时间检查一次,检查内容为指定的日志文件路径与文件名。

#推荐配置如下
open_log_file_cache max=1000 inactive=20s min_uses=2 valid=1m;

日志的格式和命令

主配置文件中的log_format将规定本机中全部的Nginx的日志格式的记录形式。

#基本样式
log_format conbined '$remote_addr - $remote_user [$time_local]'
'"$request" $statues $body_bytes_sent'
'"$http_referer" "$http_user_agent"';

日志中允许包含的标量

$romote_addr,$http_x_forwarded_for
#分别为CIP 和 DIP
$remote_user
#远程用户:记录客户端的名称
[$time_local]
#本地时间
$request
#请求:URL和HTTP协议
$status
#状态:记录请求状态
$body_bytes_sent
#发送给客户端的字节数,不包含响应头的大小
$bytes_sent
#发送给客户端的总字节数
$msec
#日志写入时间。单位微妙,保留三位
$http_referer
#记录从哪个链接跳转过来的
$http_user_agen
#记录客户端浏览器的相关信息
$request_length
#请求的长度,包括请求行,请求头和请求正文
$request_time
#请求处理的事件,单位为秒,保留三位。从读入客户端的第一个字节开始到发送完最后一个字节结束
$time_iso8601
#ISO8601标准格式下的本地时间

访问日志和错误日志

即为access_logerror_log

日志缓存

  • 存在的意义:每次日志写入操作实际上是一次I/O操作,大量的日志写入会使得服务器性能下降。为了能够提高服务器的可用性,先将日志缓存下来,之后再批量写入。
  • 具体操作见上。

日志轮转和切割

  • Nginx的安装,会默认启用日志轮转。
  • Nginx自身的日志轮转规则写入到/etc/logrotate.d/nginx
create 0644 nginx nginx #创建爱你新的日志文件,属主
daily #天
rotate 10 #保留的份数
missingok #丢失不提醒
notifempyt #若为空文件则不轮转
compress #压缩
sharedsripts #轮转后脚本
postrotate
    /bin/kill -USR1 `cat/usr/ningx.pid 2>/dev/null || true endsript`

日志分析

  • 常用的字段有
$remote_addr     $1
$time_local      $4
$request         $7
$status          $9
$body_bytes_sent $10
案例实际操作
#统计 2018年9月5日 的PV量
grep '05/Sep/2018' access.log | wc -l
#统计 2018年9月5日 一天之中访问最多的10个IP
grep '05/Sep/2018' access.log | awk '{ips[$1]++} END{for(i in ips){print i,ips[i]}}' | sort -k2 -rn | head -n10
#统计 2018年9月5日 每个URL访问内容的总大小
grep '05/Sep/2018' access.log | awk '{urls[$7]++;size[$7]+=$10}' END{for(i in urls){print urls[i],size[i],i}} | srot -k1 -rn | head -n10
#统计 2018年9月5日 IP访问码为404及出现的次数($status)
grep '05/Sep/2018' error.log | awk '{if($9="404"){ip_code[$1" "$9]++}} END{for(i in ip_code){print i,ip_code[i]}}'
#统计前一分钟PV量
date=$(date -d '-1 minute' +%d/%b/%Y:%H:%M);awk -v date=$date '$0 ~ $date{i++} END{print i}' access.log

Nginx WEB模块

  • 连接状态 stub_status_module
    • 目的 展示Nginx的连接状态
    • 查询 nginx -V 2>&1 | grep stub_status
    • 启动状态模块
    server{
        location /nginx_status{
            stu_status;
            allow all;
        }
    }
    
    • 查询示例
    Active connections: 1 #当前活动的连接数
    server accepts handled requests 
    17  17  24      # 第一个17:总连接数(TCP) 第二个17(TCP) 成功的链接数 24:总共处理的请求数(HTTP)
    Reading: 0 Writing: 1 Wating:0  #Reading请求头 Writing 响应头 Waiting等待的请求数,开始了Keepalive
    
  • 随机主页 random_index_module
    • 目的 将主页设置成随机页面,是一种微调更新机制
    • 启动随机主页模块
    server{
    
        location / {
            #root /usr/share/nginx/html;
            #index index.html;
            root /app;
            random_index on;
            #隐藏文件不会被作为随机主页显示
        }
    }
    
  • 替换模块 sub_module
    • 目的 网页内容替换 针对模板生成网页时出现的批量错误
    • 启动替换1
    server{
    
        sub-filter nginx'aaa';
        sub_filter_once on;
        location / {
          ...
        }
    }
    
  • 文件读取 ngx_http_core_module
    • 默认启动提升传输效率
  • 文件压缩 ngx_http_gzip_module
    • 语法
    Syntax: gzip on|off;
    Default: gzip off;
    Context: http,server,location,if in location
    
    Syntax: gzip_comp_level level;
    Default: gzip_comp_level 1;
    Context: http,server,location
    #压缩等级
    
    Syntax: gzip_http_version 1.0 | 1.1;
    Default: gzip_hjttp_version 1.1
    Context: http,server,location
    
    • 启动模块,传输前压缩,提高传输效率。
    • 启动
    http{
    
        gzip on;
        gzip_http_version 1.1;
        gzip_comp_level 2;
        gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
        gzip_static on;
    }
    
  • 浏览器缓存 ngx_http_headers_module
    • 语法
    Syntax:   expires [modified] time;
    Default:  expires off;
    Context:  http,server,location,if in location
    
    • 开启
      location / {
          root /app/aaa.com;
          index index.html
          expires 24h;
      }
    
  • 防盗链 ngx_http_referer_module
    • 语法
      Syntax: valid_referers none | blocked | server_names| string ...;
      Default: --
      Context: server,location
    
    • 启用
      location / {
    
          valid_referers none blocked *.a.com;
          if ($invalid_referer){
              return 403;
          }
      }
    

你可能感兴趣的:(Nginx基础)