Linux服务 Nginx(二)

Linux服务 Nginx(二)
    最权威的资料:官方文档http://nginx.org/en/docs/
    
    主配置段的指令:
        正常运行的必备配置;
            1.user USERNAME [GROUPNAME]    指定运行worker进程的用户和组;
                Syntax:    user user [group];
                Default:    user nobody nobody;
                Context:    main
            2.pid /path/to/pid_file        指定nginx守护进程的pid文件;
                Syntax:    pid file;
                Default:    pid logs/nginx.pid;
                Context:    main
            3.worker_rlimit_nofile #        指定所有worker进程多能够打开的最大文件句柄数;
                Syntax:    worker_rlimit_nofile number;
                Default:    —
                Context:    main
                linux系统中用户默认能打开的最大文件数为1024;对于任何一个服务器软件来讲,如果它要监听在某个套接字上,那么任何一个客户端来连接之后,它都会提供一个套接字文件来维持这个连接,linux就是靠这种特性来维持一切皆文件的思想;所以nginx要是同时支持一万个连接连进来,就要创建一万个套接字文件,所以我们要给运行woeker程序的用户身份赋予可以打开更多文件的权限;
        性能优化相关的配置;
            1.worker_processes #        所能够打开的worker进程的个数,通常应该少于CPU物理核心数,至少留一个核心给系统自己使用;支持自动设定;
                Syntax:    worker_processes number | auto;
                Default:    worker_processes 1;
                Context:    main
            2.worker_cpu_affinity cpumask    进行进程与cpu的绑定,可以提高缓存的命中率;但是无法避免context switch(进程的切换会产生CPU不必要消耗);    
                Syntax:    worker_cpu_affinity cpumask ...;
                        worker_cpu_affinity auto [cpumask];
                Default:    —
                Context:    main
            cpumask:
                比如有四个cpu可以这样表示:
                    0001
                    0010
                    0100
                    1000
                例子:
                    worker_processes    4;
                    worker_cpu_affinity 0001 0010 0100 1000;
                    
                    worker_processes    2;
                    worker_cpu_affinity 0101 1010;
                
            3.timer_resolution interval    减少worker进程中的计时器解析度,也就是减少gettimeofday()这个系统调用执行的次数;解析次数越多消耗cpu越多,精准度越高,解析次数越少,消耗cpu越少,精准度越低;
                Syntax:    timer_resolution interval;
                Default:    —
                Context:    main
            4.worker_priority number        指明worker进程优先级;通过设置nice值来调整优先级;
                Syntax:    worker_priority number;
                Default:    worker_priority 0;
                Context:    main
                    nice: -20  -  20,数字越小优先级越高;
        事件相关的配置;
            1.accept_mutex on|off    master调度用户请求至各worker进程时使用的负载均衡锁;on表示让多个worker轮流地去响应新请求;
                Syntax:    accept_mutex on | off;
                Default:    accept_mutex off;
                Context:    evens
            2.lock_file file    accept_mutex用到的锁文件路径;
                Syntax:    lock_file file;
                Default:    lock_file logs/nginx.lock;
                Context:    main
            3.use method    指定使用的事件模型,建议让nginx自动选择;
                method:selece,poll,kqueue,epoll,/dev/poll,eventpoll;
                Syntax:    use method;
                Default:    —
                Context:    events
            4.worker_connections number        单个worker所能够接受的做大并发连接数;
                Syntax:    worker_connections number;
                Default:    worker_connections 512;
                Context:    events
                总共的最大请求并发数=worker_connections * worker_processes    
        用于调试,定位问题的配置;    编译安装是需要开--with-debug,否则设置了这些选项也没用;
            1.daemon on|off        是否以守护进程的方式运行nginx;
                Syntax:    daemon on | off;
                Default:    daemon on;
                Context:    main
            2.master_process on|off    是否以master/worker模型来运行nginx;
                Syntax:    master_process on | off;
                Default:    master_process on;
                Context:    main
            3.error_log 位置 级别        指明错误日志的记录位置;
                    位置:file,stderr,syslog:server=address,memory:size.
                    级别:debug, info, notice, warn, error, crit, alert, or emerg.
                Syntax:    error_log file [level];
                Default:    error_log logs/error.log error;
                Context:    main, http, mail, stream, server, location
        Note:经常需要进程调整的参数:
            worker_processes,worker_connections,worker_cpu_affinity,worker_priority.
        nginx命令:
            -s [stop|quit|reopen|reload]:向nginx传递一个参数;
            
        Nginx作为web服务器时使用的配置;
            http {
            …
            }    :由ngx_http_core_module模块引入,可以实现静态的web服务器功能,就像httpd一样;
             配置框架:
                http {
                    upstream {
                        …
                    }
                    server {
                        location URL {
                            root “/path/to/somedir”;
                            …
                        }    :类似于httpd中的<Location>,用于定义URL与本地文件系统的映射关系;
                        location URL {
                            if … {
                                ...
                            }
                        …
                    }    :这里的server类似于httpd中的<VirtualHost>;
                    server {
                        …
                    }
                    
                Note:与http相关的指令,必须放在server{},location{},if{},upstream{}中,但有些指令只能应用于这五种上下文中的某些种;
            配置指令:
                1.server{}:定义一个虚拟主机;
                例子:
                 mkdir -pv /vhosts/web1
                vim /vhosts/web1/index.html
                    <h1>web1</h1>
                server {
                    listen 8080;
                    server_name www.guowei.com;
                    root "/vhosts/web1";
                }
                然后重启nginx服务,如果显示:nginx: [error] invalid PID number "" in "/var/run/nginx/nginx.pid"的话;执行nginx -c /etc/nginx/nginx.conf即可,次条命令是重新指定nginx的配置文件;
                netstat -nultp | grep 80
                tcp        0      0 0.0.0.0:8080                0.0.0.0:*                   LISTEN      2932/nginx          
                tcp        0      0 0.0.0.0:80                    0.0.0.0:*                   LISTEN      2932/nginx  
                浏览器键入:http://192.168.102.128:8080
                2.listen :指定监听的地址以及接口;
                    Syntax:    listen address[:port] ;
                            listen port ;
                            listen unix:path ;→指定其监听在unix的sock上,如果设置此项则客户端只能是本机;
                    Default:    listen *:80 | *:8000;
                    Context:    server
                    例子:
                        listen 0.0.0.0:80;
                        listen 8080;
                        listen unix:/var/run/nginx.sock;
                3.server_name name […] :指定主机名,后可跟多个主机名,名称还可以使用正则表达式(使用正则时用”~”开头)或通配符;
                    Syntax:    server_name name ...;
                    Default:    server_name "";
                    Context:    server
                    例子:
                        server {
                            server_name example.com *.example.com www.example.*;
                        }
                    当有多个server{}时,就会有多个server_name且其中有几个都符合匹配条件时,这时会按照一定的规则进行先后匹配:精确匹配(www.google.com)→ 左侧通配符匹配(*.google.com)→ 右侧通配符匹配(mail.*)→ 正则表达式匹配(~^.*.google.com$)→ 默认服务器(default_server).
                4.root path :设置资源路径映射关系,用于指明请求的URL所对应的资源所在的文件系统上的起始路径;
                    Syntax:    root path;
                    Default:    root html;
                    Context:    http, server, location, if in location
                5.location {} :允许根据用户请求的URI来匹配定义的各location;匹配到时,此请求将被相应的location配置块中的配置所处理,例如:做访问控制等功能;一个server{}中可以有多个location{};
                    Syntax:    location [ = | ~ | ~* | ^~ ] uri { ... }
                            location @name { ... }
                    Default:    —
                    Context:    server, location
                        = :精确匹配;
                        ~ :正则表达式模式匹配,区分字符大小写;
                        ~* :正则表达式模式匹配,不区分字符大小写;
                        ^~ :URI的前半部分匹配,不支持正则表达式;
                        匹配优先级:=→ ^~→ ~→ ~*→ 无特殊符号的路径;
                    例子:
                        server {
                            listen 80;
                            server_name www.guowei.com;
                            location / {
                                root “/vhosts/web1”;
                            }    :表示当访问www.guowei.com时,其实访问的是www.guowei.com/vhosts/web1/
                            location /images/ {
                                root “/vhosts/”;
                            }    :表示当访问www.guoei.com/images时,其实访问的是www.guowei.com/vhosts/images/
                            location ^~ /images/ {
                                [ configuration D ]
                            }
                            location ~* .(gif|jpg|jpeg)$ {
                                [ configuration E ]
                            }
                        }    例子:当访问/images/1.gif时,就会优先匹配第三个;
                6.alias path :定义路径别名;
                    Syntax:    alias path;
                    Default:    —
                    Context:    location
                    Note:root表示指明路径为对应的location “/”URL也就是说location后面的路径是直接接在root路径后的;ailas表示路径映射,即location指令后定义的URL是相对alias所指明的路径而言,也就是直接使用alias后面的路径取代location后面的路径;注意:如果location中的路径以”/”结尾,则alias中的路径也要以”/”结尾;
                7.index file :  设置主页面格式;由ngx_http_index_module提供;
                    Syntax:    index file ...;
                    Default:    index index.html;
                    Context:    http, server, location
                8.error_page :根据http的响应状态码为其提供专门的信息提示页面(200,404等);
                    = :表示将一种响应状态码改变成另一种状态码
                    例子:error_page 404 =200 /empty.gif;   将404变成200,然后显示/empty.gif这个图片;
                    Syntax:    error_page code ... [=[response]] uri;
                    Default:    —
                    Context:    http, server, location, if in location
                9.基于IP的访问控制:由ngx_http_access_module提供;
                    allow
                        Syntax:    allow address | CIDR | unix: | all;
                        Default:    —
                        Context:    http, server, location, limit_except
                    deny
                        Syntax:    deny address | CIDR | unix: | all;
                        Default:    —
                        Context:    http, server, location, limit_except
                    例子:
                        location / {
                            deny  192.168.1.1;
                            allow 192.168.1.0/24;
                            allow 10.1.1.0/16;
                            allow 2001:0db8::/32;
                            deny  all;
                        }
                10.基于用户的访问控制:由ngx_http_auth_basic_module提供;
                    auth_basic string :展示一些提示信息;
                        Syntax:    auth_basic string | off;
                        Default:    auth_basic off;
                        Context:    http, server, location, limit_except
                    auth_basic_user_file file :提供帐号密码文件;
                        Syntax:    auth_basic_user_file file;
                        Default:    —
                        Context:    http, server, location, limit_except
                    Note:建议使用
                        例子:
                            location / {
                                    root "/vhosts/web1/";
                                 auth_basic "Only VIP do it!";
                                    auth_basic_user_file /etc/nginx/users/.htpasswd;
                               }
                            mkdir /etc/nginx/users
                            htpasswd -c -m /etc/nginx/users/.htpasswd guowei
                            浏览器键入:http://192.168.102.128:8080
                11.https服务: 由ngx_http_ssl_module提供;
                    生成私钥,生成证书签署请求,并获得证书;
                        server {
                            listen       443 ssl;
                            server_name  localhost;

                            ssl_certificate      cert.pem;  证书文件位置;
                            ssl_certificate_key  cert.key; 私钥文件位置;

                            ssl_session_cache    shared:SSL:1m;
                            ssl_session_timeout  5m;

                            ssl_ciphers  HIGH:!aNULL:!MD5;
                            ssl_prefer_server_ciphers  on;

                            location / {
                                root   html;
                                index  index.html index.htm;
                            }
                        }
                12.stub_status on|off: 状态页;
                    Syntax:    status;
                    Default:    —
                    Context:    location
                    例子:
                        location /status {
                                    stub_status on;
                                    allow 192.168.102.0/24;
                                    deny all;
                            }
                        浏览器键入:http://192.168.102.128:8080/status
                        Active connections: 2      活动连接数;
                        server accepts handled requests    
                         12 12 23     已经接受的连接    已经处理的连接    处理的请求
                        Note:在保持连接模式下,请求数量可能会多于连接数量;
                        Reading: 0 Writing: 1 Waiting: 1     
                        Reading:正处于接收状态的的连接数;
                        Writing: 请求已经接收完成,正处于处理请求或发送响应的过程中的连接数;
                        Waiting:保持连接模式,且处于活动状态的连接数;
                13.rewrite regex replacement [flag] :实现URL重写;
                    Syntax:    rewrite regex replacement [flag];
                    Default:    —
                    Context:    server, location, if
                    flag:
                        last :重新匹配被重写的URL;URL被重写后,浏览器会使用新的URL重新向服务器发起请求,这个新的URL还会经过rewrite匹配;所以编写rewrite时注意不要形成循环;
                        break :一旦URL重写后,不会再匹配本location中的任何其他规则;
                        redirect :以302响应码(临时重定向),返回新的URL; replacrmen为http://XXXXXX
                        permanent :以301响应码(永久重定向),返回新的URL;
                    例子:rewrite ^(/download/.*)/audio/(.*)..*$ $1/mp3/$2.ra  last;
                        http://www.guowei.com/download/audio/file → http://www.guowei.com/download/mp3/file.ra  
                14.if :条件判断;
                    Syntax:    if (condition) { ... }
                    Default:    —
                    Context:    server, location
                    condition:
                        1.变量名:如果变量值为空字符串或者为0,则为false,否则为true;
                        2.以变量为操作数,构成的比较表达式;
                            =,!=等;
                        3.正则表达式的模式匹配操作;
                            ~ :区分字符大小写的匹配检查;
                            ~* :不区分字符大小写的匹配检查;
                            !~和!~*:对上面两种规取反;
                        4.测试文件的存在性;
                            -f , !-f;
                        5.测试指定路径是否为目录;
                            -d , !-d;
                        6.测试文件的存在与否;
                            -e , !-e;
                        7.检查文件是否有执行权限;
                            -x , !-x;
                        例子:
                            if ($http_user_agent ~ MSIE) {
                                rewrite ^(.*)$ /msie/$1 break;
                            }
                                Note:MSIE为客户端的浏览器类型;
                            if ($http_cookie ~* "id=([^;]+)(?:;|$)") {
                                set $id $1;
                            }
                15.防盗链;
                    location ~* .(jpg|gif|jpeg|png)& {
                        vaild_referer none blocked www.guowei.com;   指定授权网址;
                        if ($invalid_referer) {
                            rewrite ^/ http://www.guowei.com/403.html;
                        }
                    }
                16.定制访问日志格式:
                    Syntax:    log_format name [escape=default|json|none] string ...;
                    Default:    log_format combined "...";
                    Context:    http
                    例子:
                    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  logs/access.log  main;
                    Note:此处可用变量为nginx各模块内置变量;
        网络连接相关的配置;
            1.keepalive_timeout number :长连接的超时时长;
            2.keepalive_requests number :在一个长连接上所能够允许请求的最大资源数;
            3.keepalive_disable [msie6|safari|none] :为指定类型的user_agent禁用长连接;
            4.tcp_nodelay on|off :
                tcp相对来说是一种开销比较大的连接类型,因为任何一个连接建立拆除,都要经过三次握手建立连接和四次挥手断开连接,如果我们要请求很多小的数据,那么我们付出的代价就会很大,有大量的资源被浪费掉,所以tcp在其拥塞避免算法中提供可一个机制:将小的数据合并成一个大的数据再发送;但是有的时候我们又不能等待这中延时,所以是否使用要根据情况确定,on表示不合并,off表示合并;
            5.client_header_timeout number :指定读取http请求报文首部的超时时长;
            6.client_body_timeout number :指定读取http请求报文的body部分的超时时长;
            7.send_timeout number :指定发送响应报文的超时时长;
            

            注:根据马哥视频做的学习笔记,如有错误,欢迎指正;侵删;

原文地址:https://www.cnblogs.com/guowei-Linux/p/11072869.html