Clannaddada

导航

nginx配置文件详解

nginx配置文件详解

nginx配置文件

主配置文件:/usr/local/nginx/conf/nginx.conf
默认启动nginx时,使用的配置文件是:安装路径/conf/nginx.conf文件
可以在启动nginx时通过-c选项来指定要读取的配置文件
nginx常见的配置文件及其作用

配置文件 作用
nginx.conf nginx的基本配置文件
mime.types MIME类型关联的扩展文件
fastcgi.conf 与fastcgi相关的配置
proxy.conf 与proxy相关的配置
sites.conf 配置nginx提供的网站,包括虚拟主机

nginx.conf配置详解

nginx.conf的内容分为以下几段:

  • main配置段:全局配置段。其中main配置段中可能包含event配置段
  • event {}:定义event模型工作特性
  • http {}:定义http协议相关的配置

配置指令:要以分号结尾,语法格式如下:

derective value1 [value2 ...];
支持使用变量:

内置变量:模块会提供内建变量定义
自定义变量:set var_name value

用于调试、定位问题的配置参数

daemon {on|off};            //是否以守护进程方式运行nginx,调试时应设置为off
master_process {on|off};    //是否以master/worker模型来运行nginx,调试时可以设置为off
error_log 位置 级别;         //配置错误日志
error_log里的位置和级别能有以下可选项:
位置 级别
file
stderr
syslog:server=address[,parameter=value]
memory:size
debug:若要使用debug级别,需要在编译nginx时使用–with-debug选项
info
notice
warn
error
crit
alert
emerg

正常运行必备的配置参数

user USERNAME [GROUPNAME];    //指定运行worker进程的用户和组
pid /path/to/pid_file;        //指定nginx守护进程的pid文件
worker_rlimit_nofile number;  //设置所有worker进程最大可以打开的文件数,默认为1024
worker_rlimit_core size;      //指明所有worker进程所能够使用的总体的最大核心文件大小,保持默认即可

优化性能的配置参数

worker_processes n;                 //启动n个worker进程,这里的n为了避免上下文切换,通常设置为cpu总核心数-1或等于总核心数

worker_cpu_affinity cpumask ...;    //将进程绑定到某cpu中,避免频繁刷新缓存
//cpumask:使用8位二进制表示cpu核心,如:
    0000 0001   //第一颗cpu核心
    0000 0010   //第二颗cpu核心
    0000 0100   //第三颗cpu核心
    0000 1000   //第四颗cpu核心
    0001 0000   //第五颗cpu核心
    0010 0000   //第六颗cpu核心
    0100 0000   //第七颗cpu核心
    1000 0000   //第八颗cpu核心

timer_resolution interval;          //计时器解析度。降低此值,可减少gettimeofday()系统调用的次数

worker_priority number;             //指明worker进程的nice值

6.5 事件相关的配置:event{}段中的配置参数
accept_mutex {off|on};              //master调度用户请求至各worker进程时使用的负载均衡锁;on表示能让多个worker轮流地、序列化地去响应新请求

lock_file file;                     //accept_mutex用到的互斥锁锁文件路径
use [epoll | rtsig | select | poll];    //指明使用的事件模型,建议让nginx自行选择
worker_connections #;                   //每个进程能够接受的最大连接数

网络连接相关的配置参数

keepalive_timeout number;                 //长连接的超时时长,默认为65s
keepalive_requests number;                //在一个长连接上所能够允许请求的最大资源数
keepalive_disable [msie6|safari|none];    //为指定类型的UserAgent禁用长连接
tcp_nodelay on|off;                       //是否对长连接使用TCP_NODELAY选项,为了提升用户体验,通常设为on
client_header_timeout number;             //读取http请求报文首部的超时时长
client_body_timeout number;               //读取http请求报文body部分的超时时长
send_timeout number;                      //发送响应报文的超时时长

fastcgi的相关配置参数

LNMP:php要启用fpm模型
配置示例如下:

location ~ \.php$ {
  root html;
  fastcgi_pass 127.0.0.1:9000;      //定义反向代理
  fastcgi_index index.php;
  fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
  include fastcgi_params;
}

nginx作为web服务器时使用的配置

http{}段的配置参数

http{…}:配置http相关,由ngx_http_core_module模块引入。nginx的HTTP配置主要包括四个区块,结构如下:

http {              //协议级别
  include mime.types;
  default_type application/octet-stream;
  keepalive_timeout 65;
  gzip on;
  upstream {        //负载均衡配置
    ...
  }
  server {          //服务器级别,每个server类似于httpd中的一个<VirtualHost>
    listen 80;
    server_name localhost;
    location / {    //请求级别,类似于httpd中的<Location>,用于定义URL与本地文件系统的映射关系
      root html;
      index index.html index.htm;
    }
  }
}

http{}段配置指令

server {}:定义一个虚拟主机,示例如下:

server {
  listen 80;
  server_name www.idfsoft.com;
  root "/vhosts/web";
}

listen:指定监听的地址和端口

listen address[:port];
listen port;
server_name NAME [...]; 后面可跟多个主机,名称可使用正则表达式或通配符

当有多个server时,匹配顺序如下:

  1. 先做精确匹配检查
  2. 左侧通配符匹配检查,如*.idfsoft.com
  3. 右侧通配符匹配检查,如mail.*
  4. 正则表达式匹配检查,如~ ^.*.idfsoft.com$
  5. default_server
  • root path; 设置资源路径映射,用于指明请求的URL所对应的资源所在的文件系统上的起始路径

  • alias path; 用于location配置段,定义路径别名

  • index file; 默认主页面
    index index.php index.html;

  • error_page code […] [=code] URI | @name 根据http响应状态码来指明特用的错误页面,例如 error_page 404 /404_customed.html

    [=code]:以指定的响应码进行响应,而不是默认的原来的响应,默认表示以新资源的响应码为其响应码,例如 error_page 404 =200 /404_customed.html

log_format 定义日志格式

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;
 
//注意:格式名main可自己定义,但要一一对应,另外此处可用变量为nginx各模块内建变量

location区段,通过指定模式来与客户端请求的URI相匹配

//功能:允许根据用户请求的URI来匹配定义的各location,匹配到时,此请求将被相应的location配置块中的配置所处理,例如做访问控制等功能
 
//语法:location [ 修饰符 ] pattern {......}
常用修饰符说明:
修饰符 功能
= 精确匹配
~ 正则表达式模式匹配,区分大小写
~* 正则表达式模式匹配,不区分大小写
^~ 前缀匹配,类似于无修饰符的行为,也是以指定模块开始,不同的是,如果模式匹配,那么就停止搜索其他模式了,不支持正则表达式
@ 定义命名location区段,这些区段客户端不能访问,只可以由内部产生的请求来访问,如try_files或error_page等

查找顺序和优先级:由高到底依次为

  1. 带有=的精确匹配优先
  2. 带有^~修饰符的,开头匹配
  3. 正则表达式按照他们在配置文件中定义的顺序
    带有*修饰符的,如果正则表达式与URI匹配
  4. 没有修饰符的精确匹配

优先级如下:

( location = 路径 ) --> ( location ^~ 路径 ) --> 
( location ~ 正则 ) --> ( location ~* 正则 ) --> 
( location 路径 )

location实战

[root@nginx ~]# cd /usr/local/nginx/conf
[root@nginx conf]# vim nginx.conf
...
    server {
        listen       80;
        server_name  localhost;
        
        location / {		//模糊匹配"/"开头的URI,这个优先级最低,当其他的都匹配不到时,匹配这个
            echo  "/";
        }
        location = /abc {	//精确匹配URI为"/abc"
            echo "= abc";
        }
        location ^~ /abc {	//匹配以"/abc"开头的URI,优先级低于修饰符"="
            echo "^abc";
        }
        location ~ ^/a {	//使用正则表达式匹配以"a"开头的URI,优先级低于修饰符"^~"
            echo "^/a";
        }
...
[root@nginx conf]# cd
[root@nginx ~]# systemctl reload nginx.service 
 
#进行测试

#1.这次访问的的是"/abc",它的URI就是"/abc",被"location = /abc"精确匹配到,所以说修饰符"="优先级最高,打印了"=abc"
[root@nginx ~]# curl http://127.0.0.1/abc
= abc
##注意"?"后面部分不属于URI,所以说还能被"location = /abc",精确匹配到
[root@nginx ~]# curl http://127.0.0.1/abc?aa
= abc
 
#2.访问这个的URI是"/abc/",所以说不能被"location = /abc"精确匹配到,但是这个URI是以"/abc"开头的,所以说被"location ^~ /abc"优先匹配到
[root@nginx ~]# curl http://127.0.0.1/abc/
^abc
[root@nginx ~]# curl http://127.0.0.1/abc/abc
^abc
[root@nginx ~]# curl http://127.0.0.1/abcd/a
^abc
[root@nginx ~]# curl http://127.0.0.1/abcdef?aa
^abc
 
#3.只要不被前两条匹配到,且以"a"开头的URI,就都会被"location ~ ^/a"匹配到
[root@nginx ~]# curl http://127.0.0.1/a
^/a
[root@nginx ~]# curl http://127.0.0.1/ab
^/a
[root@nginx ~]# curl http://127.0.0.1/a/a?a
^/a
 
#5.只要上面的条件都不被匹配到"/",符合条件的只有"location /"这一条
[root@nginx ~]# curl http://127.0.0.1
/
[root@nginx ~]# curl http://127.0.0.1/
/
[root@nginx ~]# curl http://127.0.0.1/b
/
[root@nginx ~]# curl http://127.0.0.1/b/a
/
[root@nginx ~]# curl http://127.0.0.1/b/a?a
/

nginx访问控制

用于location段
allow:设定允许哪台或哪些主机访问,多个参数间用空格隔开
deny:设定禁止哪台或哪些主机访问,多个参数间用空格隔开
示例:

[root@nginx ~]# cd /usr/local/nginx/html/
[root@nginx html]# ls
50x.html  index.html
[root@nginx html]# echo 'hello world' > index.html 
[root@nginx html]# systemctl restart nginx

#虚拟机访问
[root@nginx html]# curl 192.168.111.141
hello world

浏览器访问

修改配置文件设置访问权限,设置只允许虚拟机访问

[root@nginx html]# cd ..
[root@nginx nginx]# vim conf/nginx.conf
...
        location / {
            allow 192.168.118.129;
            deny all;
            root   html;
            index  index.html index.htm;
        }
...
[root@nginx nginx]# systemctl restart nginx

#虚拟机访问
[root@nginx nginx]# curl 192.168.118.129
hello world

主机浏览器访问

image

nginx用户认证

#安装httpd工具包
[root@nginx ~]# yum -y install httpd-tools

[root@nginx ~]# cd /usr/local/nginx/html/
[root@nginx html]# mkdir abc
[root@nginx html]# echo "ABC" >> abc/index.html

#修改配置文件
[root@nginx html]# cd
[root@nginx ~]# cd /usr/local/nginx/conf/
[root@nginx conf]# vim nginx.conf
...
        location /abc { 
             auth_basic "ABC"; 
             auth_basic_user_file "/usr/local/nginx/conf/.pass"; 	#密码位置 
             root html;
             index index.html;
        }
...

#生成密码
[root@nginx conf]# htpasswd -cm /usr/local/nginx/conf/.pass daxinyu
New password: 
Re-type new password: 
Adding password for user daxinyu
[root@nginx conf]# cat .pass 
daxinyu:$apr1$adGf7vfN$G9eStSLIcBg4Eq7xCQN5q.
[root@nginx conf]# systemctl restart nginx

直接访问

image

访问html下的abc

image

image

https配置

证书申请及签署步骤

a) 生成申请请求

b) RA核验

c) CA签署

d) 获取证书

#生成证书
[root@nginx ~]# cd /etc/pki/
[root@nginx pki]# mkdir CA
[root@nginx pki]# cd CA/
[root@nginx CA]# mkdir private
[root@nginx CA]# (umask 077;openssl genrsa -out private/cakey.pem 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
.............................................+++++
......+++++
e is 65537 (0x010001)
[root@nginx CA]# ls private/
cakey.pem

#CA生成自签署证书
[root@nginx CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 365
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN         #国家
State or Province Name (full name) []:HB     #省份
Locality Name (eg, city) [Default City]:WH   #城市
Organization Name (eg, company) [Default Company Ltd]:DXY     
Organizational Unit Name (eg, section) []:www.example.com
Common Name (eg, your name or your server's hostname) []:www.example.com
Email Address []:123@456.com
[root@nginx CA]# mkdir certs newcerts crl
[root@nginx CA]# touch index.txt && echo 01 > serial

#生成秘钥
[root@nginx CA]# cd /usr/local/nginx/conf/
[root@nginx conf]# mkdir ssl
[root@nginx conf]# cd ssl/
[root@nginx ssl]# (umask 077;openssl genrsa -out nginx.key 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
...............................................................................................+++++
.......................................+++++
e is 65537 (0x010001)

#证书签署请求
[root@nginx ssl]# openssl req -new -key nginx.key -days 365 -out nginx.csr
Ignoring -days; not generating a certificate
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:HB
Locality Name (eg, city) [Default City]:WH
Organization Name (eg, company) [Default Company Ltd]:DXY
Organizational Unit Name (eg, section) []:www.example.com
Common Name (eg, your name or your server's hostname) []:www.example.com
Email Address []:123@456.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:          #回车
An optional company name []:      #回车

#签署证书
[root@nginx ssl]# openssl ca -in nginx.csr -out nginx.crt -days 365
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Oct 13 14:51:04 2022 GMT
            Not After : Oct 13 14:51:04 2023 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = HB
            organizationName          = DXY
            organizationalUnitName    = www.example.com
            commonName                = www.example.com
            emailAddress              = 123@456.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                78:F8:8D:3E:C8:C6:F0:4C:CB:B3:BD:DA:0B:C6:C2:02:6B:01:A1:0F
            X509v3 Authority Key Identifier: 
                keyid:26:DD:53:90:8B:BA:13:01:83:CA:7A:02:34:71:5A:9E:10:5E:E7:73

Certificate is to be certified until Oct 13 14:51:04 2023 GMT (365 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
[root@nginx ssl]# ls
nginx.crt  nginx.csr  nginx.key

#修改配置文件加入生成的秘钥和证书
[root@nginx ssl]# cd ..
[root@nginx conf]# vim nginx.conf
//先取消注释
    server {
        listen       443 ssl;
        server_name  www.example.com;

        ssl_certificate      /usr/local/nginx/conf/ssl/nginx.crt;	#修改为密钥和证书的位置
        ssl_certificate_key  /usr/local/nginx/conf/ssl/nginx.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;
        }
    }

}
[root@nginx conf]# systemctl restart nginx

访问测试

image

点高级继续前往

image

状态页面开启和监控

开启状态页面

开启status:

location /status {
  stub_status {on | off};      //默认off
  allow 172.16.0.0/16; 
  deny all;                    //设置可以访问的IP
}

访问状态页面的方式:

http://server_ip/status

访问测试

image

状态页面信息详解:

状态码 表示的意义
Active connections 2 当前所有处于打开状态的连接数
accepts 总共处理了多少个连接
handled 成功创建多少握手
requests 总共处理了多少个请求
Reading nginx读取到客户端的Header信息数,表示正处于接收请求状态的连接数
Writing nginx返回给客户端的Header信息数,表示请求已经接收完成, 且正处于处理请求或发送响应的过程中的连接数
Waiting 开启keep-alive的情况下,这个值等于active - (reading + writing), 意思就是Nginx已处理完正在等候下一次请求指令的驻留连接

监控状态页面

环境介绍

主机名 ip 服务
zabbix 192.168.118.137 LAMP
zabbix-server
zabbix-agentd
nginx 192.168.118.129 nginx
zabbix-agentd

nginx端

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
...
        location = /nginx_status {
            stub_status on;
        }
...
[root@nginx ~]# systemctl restart nginx

image

nginx部署zabbix监控链接

#创建用户
[root@nginx ~]# useradd -rMs /sbin/nologin zabbix

#下载相关依赖包
[root@nginx ~]# dnf -y install make gcc gcc-c++ pcre-devel openssl openssl-devel

#下载,解压,编译安装zabbix_agentd
[root@nginx ~]# wget https://cdn.zabbix.com/zabbix/sources/stable/6.2/zabbix-6.2.2.tar.gz
[root@nginx ~]# tar -xf zabbix-6.2.2.tar.gz
[root@nginx ~]# cd zabbix-6.2.2
[root@nginx zabbix-6.2.2]# ./configure --enable-agent
[root@nginx zabbix-6.2.2]# make install

#修改配置文件
[root@nginx ~]# vim /usr/local/etc/zabbix_agentd.conf
Server=192.168.118.137			//修改为服务端IP地址

ServerActive=192.168.118.137			//agent主动模式

Hostname=nginx			//zabbix系统内主机名

#启动服务
[root@nginx ~]# zabbix_agentd 
[root@nginx ~]# ss -antl
State     Recv-Q    Send-Q       Local Address:Port        Peer Address:Port   Process    
LISTEN    0         128                0.0.0.0:22               0.0.0.0:*                 
LISTEN    0         128                0.0.0.0:443              0.0.0.0:*                 
LISTEN    0         128                0.0.0.0:10050            0.0.0.0:*                 
LISTEN    0         128                0.0.0.0:80               0.0.0.0:*                 
LISTEN    0         128                   [::]:22                  [::]:* 

#监控编写脚本
[root@nginx ~]# mkdir /scripts
[root@nginx ~]# cd /scripts/
[root@nginx scripts]# vi check_nginx.sh
#Script to fetch nginx statuses for monitoring systems

HOST="127.0.0.1"
PORT="80"

function ping {
    /sbin/pidof nginx | wc -l
}

function active {
    /usr/bin/curl "http://$HOST:$PORT/nginx_status/" 2>/dev/null| grep 'Active' | awk '{print $NF}'
}
function reading {
    /usr/bin/curl "http://$HOST:$PORT/nginx_status/" 2>/dev/null| grep 'Reading' | awk '{print $2}'
}
function writing {
    /usr/bin/curl "http://$HOST:$PORT/nginx_status/" 2>/dev/null| grep 'Writing' | awk '{print $4}'
}
function waiting {
    /usr/bin/curl "http://$HOST:$PORT/nginx_status/" 2>/dev/null| grep 'Waiting' | awk '{print $6}'
}
function accepts {
    /usr/bin/curl "http://$HOST:$PORT/nginx_status/" 2>/dev/null| awk NR==3 | awk '{print $1}'
}
function handled {
    /usr/bin/curl "http://$HOST:$PORT/nginx_status/" 2>/dev/null| awk NR==3 | awk '{print $2}'
}
function requests {
    /usr/bin/curl "http://$HOST:$PORT/nginx_status/" 2>/dev/null| awk NR==3 | awk '{print $3}'
}
$1
[root@zabbix scripts]# chmod +x check_nginx.sh 
[root@zabbix scripts]# ll
总用量 4
-rwxr-xr-x 1 root root 1003 10月 13 23:08 check_nginx.sh

#开启自定义监控
[root@nginx ~]# vim /usr/local/etc/zabbix_agentd.conf
#在最后添加下面两行
UnsafeUserParameters=1
UserParameter=check_nginx[*],/bin/bash /scripts/check_nginx.sh $1

#重启服务
[root@nginx ~]# pkill zabbix
[root@nginx ~]# zabbix_agentd 
[root@nginx ~]# ss -antl
State     Recv-Q    Send-Q       Local Address:Port        Peer Address:Port   Process    
LISTEN    0         128                0.0.0.0:22               0.0.0.0:*                 
LISTEN    0         128                0.0.0.0:443              0.0.0.0:*                 
LISTEN    0         128                0.0.0.0:10050            0.0.0.0:*                 
LISTEN    0         128                0.0.0.0:80               0.0.0.0:*                 
LISTEN    0         128                   [::]:22                  [::]:*    

服务端进行测试

#修改中括号内想要查看的状态名称即可
[root@zabbix ~]# zabbix_get -s 192.168.118.129 -k check_nginx[active]		
1
[root@zabbix ~]# zabbix_get -s 192.168.118.129 -k check_nginx[accepts]
4
[root@zabbix ~]# zabbix_get -s 192.168.118.129 -k check_nginx[handled]
5

创建监控主机

image

创建监控项

image

image

image

posted on 2022-10-14 00:09  linux-ada  阅读(6522)  评论(0编辑  收藏  举报