nginx-http配置介绍

2018-05-28 11:10:37

nginx工作流程图
nginx-http配置介绍

http部分工作流程大致如一个master开启多个worker,网络io一般用epoll实现当个worker的高并发,文件io用sendfile,aio等高效移步io,实现一个http请求响应。
io部分请参考:http://blog.51cto.com/marvin89/2115474

主脚本请翻阅:http://blog.51cto.com/marvin89/2118341
安装配置文件:

name: nginx
version: 1.14.0
download: http://nginx.org/download/nginx-{version}.tar.gz
cmds:
  - id nginx ||  useradd -r -M -s /sbin/nologin nginx
yum:
  - yum -y groupinstall "Development tools"
  - yum -y install pcre-devel openssl-devel zlib-devel

uncompress: tar xf nginx-{version}.tar.gz
uncompress_dir: nginx-{version}
compile: ./configure --prefix={source_path}/{name}{version}
                              --conf-path={source_path}/{name}{version}/conf/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
                              --user=nginx
                              --group=nginx
                              --with-http_ssl_module
                              --with-http_v2_module
                              --with-http_dav_module
                              --with-http_stub_status_module
                              --with-threads
                              --with-file-aio
                              --with-http_gzip_static_module
                              --add-module=../nginx-http-auth-digest-master
                              && make && make install
depends:
  - name: nginx-http-auth-digest
    version: ''
    download: 'https://github.com/atomx/nginx-http-auth-digest/archive/master.zip -O nginx-http-auth-digest-master.zip'
    uncompress: unzip nginx-http-auth-digest-master.zip
    uncompress_dir: ''
    compile: ''
init:
    linkname: nginx
    cmds:
      - cat {source_path}/{name}{version}/conf/nginx.conf|egrep 'include conf\.d/\*\.conf' || sed -i '$s#}#\tinclude conf.d/*.conf;\n}#' {source_path}/{name}{version}/conf/nginx.conf
      - '[ -d {source_path}/{name}{version}/conf/conf.d ] || mkdir {source_path}/{name}{version}/conf/conf.d'
      - echo 'export PATH={link_path}/{name}/sbin:$PATH'>/etc/profile.d/nginx.sh

    systemctl:
          path: /etc/systemd/system/mynginx.service
          content:
              Unit:
                  Description: The Nginx Server
                  After: network.target remote-fs.target nss-lookup.target
              Service:
                  Type: forking
                  PIDFILE: '/var/run/nginx.pid'
                  ExecStart: '{link_path}/{name}/sbin/nginx'
                  ExecReload: '{link_path}/{name}/sbin/nginx  -s reload'
                  ExecStop: '{link_path}/{name}/sbin/nginx -s stop'
                  PrivateTmp: true
              Install:
                  WantedBy: multi-user.target

http配置项说明

1、绑定cpu

绑定cpu场景,服务器以nginx服务为主,不然会影响其他服务性能

没有绑定前

[root@node1 test]# watch -n0.5 'ps axo comm,pid,ppid,psr|grep nginx'
Every 0.5s: ps axo comm,pid,ppid,psr|grep nginx                                                               Sun May 27 19:35:10 2018

nginx             5047      1   0
nginx             5048   5047   1
nginx             5049   5047   0
nginx             5050   5047   2

可以看到nginx进程时候会不断切换cpu

绑定cpu

worker_processes  3;
worker_cpu_affinity auto;
#worker_cpu_affinity 0001 0010 0100 1000;#绑定cpu  #如果服务器以nginx为主  这个优化是可以的(如果不是,请勿打开)   用auto就可以了
#用掩码方式绑定  假如8个cpu  0000 0000    每个0对应一个cpu
[root@node1 test]# watch -n0.5 'ps axo comm,pid,ppid,psr|grep nginx'
Every 0.5s: ps axo comm,pid,ppid,psr|grep nginx                                                               Sun May 27 19:34:18 2018

nginx             4895      1   2
nginx             4896   4895   0
nginx             4897   4895   1
nginx             4898   4895   2

#不会切换cpu,切换cpu会有很多cpu开销,以及缓存之类

2、进程调优

worker_processes auto;   #超过cpu 核数就没有意义了   lscpu可以查看   auto最大个数
worker_rlimit_nofile number    cpu个数*worker_connections    最大打开文件描述符
events {
    worker_connections  1024;      #单个进程响应请求数
    use epoll;                    #网络io复用  用epoll 
    accept_mutex on | off;   #个人推荐Off
    #处理新的连接请求的方法;on意味着由各worker轮流处理新请求,Off意味着每个新请求的到达都会通知所有的worker进程,能者多劳;
}

调整优先级

默认
nginx-http配置介绍

配置参数

worker_priority -5;

nginx-http配置介绍

3、http配置设置

server兜底配置,也可以在每个server中另外配置
When both AIO and sendfile are enabled on Linux, AIO is used for files that are larger than or equal to the size specified in the directio directive, while sendfile is used for files of smaller sizes or when directio is disabled.

http {
     include       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"';     #http_x_forwarded_for在代理服务器转发时候记录源地址

     #配置在这里是兜底用,也可以不设置,如果设置一定开启缓存,不然平凡写入太消耗io
     access_log  logs/access.log  main buffer=4096;   

     #http, server, location配置段都可以
     sendfile        on;         #高效传输文件的模式   从内核直接到发送出去,不走客户端
     tcp_nopush     on;        #在sendfile模式下,是否启用TCP_CORK选项;   一个文件一个报文发送,应用层首部一个文件只要一次,而不是分开
     aio            on;
     #tcp_nodelay on | off;
            #在keepalived模式下的连接是否启用TCP_NODELAY选项;   keepalived下 小的包可能会打包一起发送,节约带宽,但是影响客户端了
            #tcp_nodelay on 不要等待发送,提升客户端体验  如果不是保持连接,这项不存在

     #http, server, location
     keepalive_timeout  65;      #65s   
     keepalive_requests 100;     #100个资源

     #http, server, location客户端上传资料大小 post之类;超出此大小时,其将被暂存到磁盘上的由  client_body_temp_path指令所定义的位置;合理定义能小就小   16*1024 字节  5461个中文
     client_body_buffer_size 16k;
     client_max_body_size 20m;  #post 最大值
     client_body_temp_path       client_body_temp_path /dev/shm/nginx/body_temp/ 1 2 ;  #目录要在/dev/shm下面
        /dev/shm/nginx/body_temp/1/05/0000000051
        1:表示用一位16进制数字表示一级子目录;0-f
        2:表示用2位16进程数字表示二级子目录:00-ff
        2:表示用2位16进程数字表示三级子目录:00-ff

     include conf.d/*.conf;
}

4、文件io优化

文件操作优化的常用配置
aio on
open_file_cache max=N 

官方配置
open_file_cache          max=1000 inactive=20s;
open_file_cache_valid    30s;
open_file_cache_min_uses 2;
open_file_cache_errors   on;

其他否是默认值
    sendfile on  ;   内核减少复制过程  适合小文件
    aio on | off | threads[=pool];     多线程读取本地io
        是否启用aio功能;

    directio size | off;     #使用大文件读取,不会读cache或者存入buffer
        在Linux主机启用O_DIRECT标记,此处意味文件大于等于给定的大小时使用,例如directio 4m;

    open_file_cache off;
        open_file_cache max=N [inactive=time];
            nginx可以缓存以下三种信息:
                (1) 文件的描述符、文件大小和最近一次的修改时间;
                (2) 打开的目录结构;
                (3) 没有找到的或者没有权限访问的文件的相关信息;

            max=N:可缓存的缓存项上限;达到上限后会使用LRU算法实现缓存管理;

            inactive=time:缓存项的非活动时长,在此处指定的时长内未被命中的或命中的次数少于open_file_cache_min_uses指令所指定的次数的缓存项即为非活动项;

    open_file_cache_valid time;
        缓存项有效性的检查频率;默认为60s; 

    open_file_cache_min_uses number;
        在open_file_cache指令的inactive参数指定的时长内,至少应该被命中多少次方可被归类为活动项;

    open_file_cache_errors on | off;
        是否缓存查找时发生错误的文件一类的信息;

5、认证

明文

[root@node1 conf]# htpasswd -c -m .ngxpasswd tom
[root@node1 conf]# htpasswd  -m .ngxpasswd jack

location ^~ /admin/ {
      auth_basic "admin area";
      auth_basic_user_file .ngxpasswd;   #根nginx.conf同一个层级
}

密文

https://www.nginx.com/resources/wiki/modules/auth_digest/

[root@node1 conf]# htdigest -c .passwd_digest 'digest' tom
[root@node1 conf]# htdigest  .passwd_digest 'digest' jack

      location ^~ /admins/ {
                auth_digest "digest";
                auth_digest_user_file .passwd_digest;
        }

nginx-http配置介绍

6、http状态

location ^~ /basic_status/ {
        stub_status;
}

Active connections: 4 
server accepts handled requests
 25825 25825 25885 
Reading: 0 Writing: 1 Waiting: 3 

Active connections: 活动状态的连接数;
accepts:已经接受的客户端请求的总数;
handled:已经处理完成的客户端请求的总数;
requests:客户端发来的总的请求数;
Reading:处于读取客户端请求报文首部的连接的连接数;
Writing:处于向客户端发送响应报文过程中的连接数;
Waiting:处于等待客户端发出请求的空闲连接数;

7、location优先级

~:对URI做正则表达式模式匹配,区分字符大小写;
~*:对URI做正则表达式模式匹配,不区分字符大小写;
^~:对URI的左半部分做匹配检查,不区分字符大小写;
不带符号:匹配起始于此uri的所有的url;
匹配优先级:=, ^~, ~/~*,不带符号;

1   =:对URI做精确匹配
location = / {
    [ configuration A ]
}

2   ~:对URI做正则表达式模式匹配,区分字符大小写;
location ^~ /images/ {
    [ configuration D ]
}

2   ^~:对URI的左半部分做匹配检查,不区分字符大小写;
location ~* \.(gif|jpg|jpeg)$ {
    [ configuration E ]
}

3    不带符号:匹配起始于此uri的所有的url;  不带符号的长度越长优先级越高
location /images/ {
   root /webapps/app1/data/     #根/webapps/app1/data/  在根下面寻找

   #alias 匹配路径别名/images/  别名到/webapps/app1/data/ 路径下
   #http://www.test.develop/images/a.jpg    匹配/images/ 注意/;还剩a.jpg  /webapps/app1/data/必须要/    /webapps/app1/data/a.jpg
   #如果匹配的是/images;还剩/a.jpg         /webapps/app1/data[/]/a.jpg
   alias /webapps/app1/data/     
}

location / {
    [ configuration B ]
}
优先级从高到低

8、日志

access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
access_log /www/data/nginx/logs/test.log main buffer=2048;   默认是随时写入,必须设置
access_log off;

access_log path;   #每个server都可以开启一个自己的日志
location ^~ /basic_status/ {
        stub_status;
        access_log off;    #有些地址请求不要记录日志
}

open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];
open_log_file_cache off;
缓存各日志文件相关的元数据信息;

max:缓存的最大文件描述符数量;
min_uses:在inactive指定的时长内访问大于等于此值方可被当作活动项;
inactive:非活动时长;
valid:验正缓存中各缓存项是否为活动项的时间间隔;

9、压缩

nginx-http配置介绍
配置压缩

gzip  on;
gzip_comp_level 6;
gzip_min_length 64;
gzip_proxied any;
gzip_types text/xml text/css  application/javascript;

压缩后,块状传输
nginx-http配置介绍

10、rewrite

只有在location中规则才会循环,相当于以下循环
last = continue
break = break

while True:
        rewrite /(.*)\.png$     /$1.jpg break;
        rewrite /(.*)\.jpg$     /$1.png break;

死循环

location ~* \.(jpg|png)$ {
        rewrite /(.*)\.png$     /$1.jpg;      
        rewrite /(.*)\.jpg$     /$1.png;
        root /www/data/nginx/test;
        allow all;
}

break 停止rewrite匹配

location ~* \.(jpg|png)$ {
        rewrite /(.*)\.png$     /$1.jpg break;
        rewrite /(.*)\.jpg$     /$1.png break;
        root /www/data/nginx/test;
        allow all;
}

last break 只在nginx内部实现,客户端无感知
redirect 是先把匹配到的结果返回给客户端,实现302重定向

rewrite /(.*)\.png$     /$1.jpg redirect;

nginx-http配置介绍

permanent永久重定向

 rewrite /(.*)\.png$     /$1.jpg permanent;

nginx-http配置介绍

11、referer防盗链

        location ~* \.(jpg|png)$ {
                valid_referers none block  www.test.develop;
                if ($invalid_referer){
                        return 403;
                }
                rewrite /(.*)\.png$     http://www.test.develop/$1.jpg redirect;
                root /www/data/nginx/test;
                allow all;
        }

none:请求报文首部没有referer首部;
blocked:请求报文的referer首部没有值;
server_names:参数,其可以有值作为主机名或主机名模式;
    arbitrary_string:直接字符串,但可使用*作通配符;
    regular expression:被指定的正则表达式模式匹配到的字符串;要使用~打头,例如 ~.*\.zander\.com;               

转载来源http://blog.51cto.com/marvin89/2121017

©著作权归作者所有:来自51CTO博客作者朱波波的原创作品,如需转载,请注明出处,否则将追究法律责任

猜你喜欢

转载自blog.csdn.net/qq_26562641/article/details/85007268