nginx配置

本文详细介绍了nginx的配置文件、服务控制方法以及配置参数的解析。内容包括nginx的默认配置文件、服务启动选项、配置文件详解、主要配置段如main、event、http等,以及worker_processes、worker_connections等关键参数的优化。此外,还涵盖了错误日志设置、网络连接参数、fastcgi配置、虚拟主机定义、访问控制和https配置等内容,帮助读者全面掌握nginx的管理和配置技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

nginx配置

nginx默认配置文件

[root@server1 conf]# pwd
/usr/local/nginx/conf
[root@server1 conf]# ls
fastcgi.conf            nginx.conf
fastcgi.conf.default    nginx.conf.default
fastcgi_params          scgi_params
fastcgi_params.default  scgi_params.default
koi-utf                 uwsgi_params
koi-win                 uwsgi_params.default
mime.types              win-utf
mime.types.default

nginx服务控制方式

//服务控制方式,使用nginx命令
    -t  //检查配置文件语法
    -v  //输出nginx的版本
    -c  //指定配置文件的路径
    -s  //发送服务控制信号,可选值有{stop|quit|reopen|reload}

检查语法 :-t

[root@server1 ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@server1 ~]# 

nginx版本:-v

[root@server1 ~]# nginx -v
nginx version: nginx/1.20.1

指定配置文件路径: -c

[root@server1 conf]# pwd
/usr/local/nginx/conf
#把默认配置文件备份到另一个目录
[root@server1 conf]# cp nginx.conf mime.types /opt/test/
[root@server1 conf]# ls /opt/test/
mime.types  nginx.conf

#查看默认配置文件有4个worker_processes进程
[root@server1 conf]# head -5 nginx.conf

#user  nobody;
worker_processes  4;

#error_log  logs/error.log;


[root@server1 conf]# ps -ef | grep nginx
root      255627       1  0 16:06 ?        00:00:00 nginx: master process nginx
nginx     255628  255627  0 16:06 ?        00:00:00 nginx: worker process
nginx     255629  255627  0 16:06 ?        00:00:00 nginx: worker process
nginx     255630  255627  0 16:06 ?        00:00:00 nginx: worker process
nginx     255631  255627  0 16:06 ?        00:00:00 nginx: worker process
root      263190    1511  0 16:08 pts/0    00:00:00 grep --color=auto nginx



[root@server1 ~]# head -5 /opt/test/nginx.conf 

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;

[root@server1 ~]# nginx -s stop;nginx -c /opt/test/nginx.conf 
[root@server1 ~]# ps -ef | grep nginx
root      266383       1  0 16:09 ?        00:00:00 nginx: master process nginx -c /opt/test/nginx.conf
nginx     266384  266383  0 16:09 ?        00:00:00 nginx: worker process
root      266766    1511  0 16:09 pts/0    00:00:00 grep --color=auto nginx

发送服务控制信号:-s

停止服务 stop
[root@server1 ~]# nginx -s stop
[root@server1 ~]# ps -ef | grep nginx
root      333600    1511  0 16:27 pts/0    00:00:00 grep --color=auto nginx
[root@server1 ~]# ss -antl
State    Recv-Q   Send-Q       Local Address:Port                     Peer Address:Port                 
LISTEN   0        128                0.0.0.0:22                            0.0.0.0:*                    
LISTEN   0        128                   [::]:22                               [::]:*   
退出服务:quit
[root@server1 ~]# ps -ef | grep nginx
root      341196       1  0 16:30 ?        00:00:00 nginx: master process nginx
nginx     341197  341196  0 16:30 ?        00:00:00 nginx: worker process
nginx     341198  341196  0 16:30 ?        00:00:00 nginx: worker process
nginx     341199  341196  0 16:30 ?        00:00:00 nginx: worker process
nginx     341200  341196  0 16:30 ?        00:00:00 nginx: worker process
root      341923    1511  0 16:30 pts/0    00:00:00 grep --color=auto nginx

[root@server1 ~]# nginx -s quit
[root@server1 ~]# ps -ef | grep nginx
root      346758    1511  0 16:31 pts/0    00:00:00 grep --color=auto nginx

重新加载文件:reload
[root@server1 ~]# ps -ef | grep nginx
root      355450       1  0 16:33 ?        00:00:00 nginx: master process nginx
nginx     355451  355450  0 16:33 ?        00:00:00 nginx: worker process
nginx     355452  355450  0 16:33 ?        00:00:00 nginx: worker process
nginx     355453  355450  0 16:33 ?        00:00:00 nginx: worker process
nginx     355454  355450  0 16:33 ?        00:00:00 nginx: worker process
root      355606    1511  0 16:34 pts/0    00:00:00 grep --color=auto nginx
[root@server1 ~]# vim /usr/local/nginx/conf/nginx.conf
[root@server1 ~]# head -5 /usr/local/nginx/conf/nginx.conf

#user  nobody;
worker_processes  2;  #原本有四个worker process进程现在改为两个

#error_log  logs/error.log;
[root@server1 ~]# nginx -s reload    #重新加载
[root@server1 ~]# ps -ef | grep nginxroot      355450       1  0 16:33 ?        00:00:00 nginx: master process nginx
nginx     358912  355450  0 16:34 ?        00:00:00 nginx: worker process
nginx     358913  355450  0 16:34 ?        00:00:00 nginx: worker process
root      359145    1511  0 16:34 pts/0    00:00:00 grep --color=auto nginx

nginx的配置文件详解

主配置文件:/usr/local/nginx/conf/nginx.conf

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

nginx常见的配置文件及其作用

配置文件作用
nginx.confnginx的基本配置文件
mime.typesMIME类型关联的扩展文件
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:sizedebug:若要使用debug级别,需要在编译nginx时使用–with-debug选项
info
notice
warn
error
crit
alert
emerg

开启错误日志

[root@serevr1 ~]# vim   /usr/local/nginx/conf/nginx.conf
#user  nobody;
worker_processes  2;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
error_log  logs/error.log  info;

查看错误日志位置

[root@serevr1 nginx]# pwd
/var/log/nginx
[root@serevr1 nginx]# ls
access.log  cat  error.log
[root@serevr1 nginx]# cat  error.log 
2021/10/26 17:08:47 [notice] 373309#0: signal process started
2021/10/26 19:29:56 [notice] 227608#0: signal process started
2021/10/26 19:30:33 [error] 227612#0: *1 open() "/usr/local/nginx/html/favicon.ico" failed (2: No such file or directory), client: 192.168.244.1, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "192.168.244.133", referrer: "http://192.168.244.133/"

清空错误日志并改日志级别为debug

[root@serevr1 nginx]# > error.log 
[root@serevr1 nginx]# cat error.log 

[root@serevr1 ~]# vim   /usr/local/nginx/conf/nginx.conf
#user  nobody;
worker_processes  2;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
error_log  logs/error.log error ;
#重启服务
[root@serevr1 ~]# systemctl restart nginx
#查看错误日志
[root@serevr1 nginx]# cat error.log 
2021/10/26 20:16:18 [notice] 331720#0: signal process started
2021/10/26 20:18:21 [notice] 343000#0: signal process started

正常运行必备的配置参数

user USERNAME [GROUPNAME];    //指定运行worker进程的用户和组
pid /path/to/pid_file;    //指定nginx守护进程的pid文件
worker_rlimit_nofile number;    //设置所有worker进程最大可以打开的文件数,默认为1024
worker_rlimit_core size;    //指明所有worker进程所能够使用的总体的最大核心文件大
user 指定运行worker进程的用户和组
[root@serevr1 ~]# head -5  /usr/local/nginx/conf/nginx.conf

user  nginx nginx;  #修改为nginx用户  nginx组
worker_processes  2;

#error_log  logs/error.log;

重启nginx服务
[root@serevr1 ~]# systemctl restart nginx



[root@serevr1 ~]# ps -ef  | grep nginx
root      367359       1  0 20:22 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx     367360  367359  0 20:22 ?        00:00:00 nginx: worker process
nginx     367361  367359  0 20:22 ?        00:00:00 nginx: worker process
root      368896  300727  0 20:23 pts/2    00:00:00 grep --color=auto nginx

pid 指定nginx守护进程的pid文件
[root@serevr1 ~]# head -10   /usr/local/nginx/conf/nginx.conf

user  nginx nginx;
worker_processes  2;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
error_log  logs/error.log  error;

pid        logs/nginx.pid;

[root@serevr1 ~]# nginx -s reload
[root@serevr1 ~]# 
[root@serevr1 ~]# ls /usr/local/nginx/logs/
error.log  nginx.pid
[root@serevr1 ~]# nginx -s stop
[root@serevr1 ~]# ls /usr/local/nginx/logs/
error.log

worker_rlimit_nofile number 设置所有worker进程最大可以打开的文件数,默认为1024

修改worker进程的最大打开文件数限制(RLIMIT_NOFILE)在不重启主进程的情况下增加限制。

一个worker进程可以处理的请求数量



user  nginx nginx;
worker_processes  2;

worker_rlimit_nofile 10240; #一般设置为10240

优化性能的配置参数

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值
[root@serevr1 ~]# head -10  /usr/local/nginx/conf/nginx.conf

user  nginx nginx;
worker_processes  2;

worker_rlimit_nofile 10240;
worker_cpu_affinity auto ;     #添加此行

[root@serevr1 conf]# vim  nginx.conf
[root@serevr1 conf]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@serevr1 conf]# 
[root@serevr1 conf]# nginx -s reload

添加核心数

[root@serevr1 ~]# vim /usr/local/nginx/conf/nginx.conf
.......
worker_cpu_affinity 0001 0010 0100;
[root@serevr1 ~]# nginx -s stop 
[root@serevr1 ~]# nsinx

查看nginx在哪个核心上运行

[root@serevr1 ~]# top 
top - 21:15:45 up 24 min,  6 users,  load average: 0.47, 0.27, 0.19
Tasks: 243 total,   3 running, 240 sleeping,   0 stopped,   0 zombie
%Cpu(s):  2.1 us,  6.0 sy,  0.0 ni, 91.2 id,  0.0 wa,  0.3 hi,  0.3 si,  0.0 st
MiB Mem :   2807.5 total,   2056.3 free,    445.9 used,    305.3 buff/cache
MiB Swap:   2092.0 total,   2092.0 free,      0.0 used.   2196.1 avail Mem 
Locate string      #按 L(大写)  搜索nginx       

Locate string nginx


top - 21:17:46 up 26 min,  6 users,  load average: 0.45, 0.31, 0.20
Tasks: 241 total,   1 running, 240 sleeping,   0 stopped,   0 zombie
%Cpu(s):  1.2 us,  4.1 sy,  0.0 ni, 94.4 id,  0.0 wa,  0.2 hi,  0.2 si,  0.0 st
MiB Mem :   2807.5 total,   2058.1 free,    443.5 used,    306.0 buff/cache
MiB Swap:   2092.0 total,   2092.0 free,      0.0 used.   2198.5 avail Mem 

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND                                            
  41416 nginx     20   0  111724   6260   4660 S   0.0   0.2   0:00.00 nginx                                              
  41417 nginx     20   0  111724   5884   4536 S   0.0   0.2   0:00.00 nginx                                              
  52985 root      20   0       0      0      0 I   0.0   0.0   0:00.25 kworker/1:1-mm_percpu_wq                           
  75633 root      20   0       0      0      0 I   0.0   0.0   0:00.06 kworker/2:3-events_freezable                       
  81214 root      20   0       0      0      0 I   0.0   0.0   0:00.02 kworker/3:2-xfs-cil/dm-0                           
  84670 root      20   0       0      0      0 I   0.0   0.0   0:00.14 kworker/1:2-events_power_efficient                 
  95367 root      20   0       0      0      0 I   0.0   0.0   0:00.05 kworker/u256:1-events_unbound                      
 111598 root      20   0       0      0      0 I   0.0   0.0   0:00.01 kworker/3:1-xfs-sync/dm-0                          
 113156 root      20   0       0      0      0 I   0.0   0.0   0:00.26 kworker/1:0-events                                 
 122477 root      20   0   61736   4580   3672 R   0.0   0.2   0:00.06 top                                                
 133755 root      20   0   15128   3328   3000 S   0.0   0.1   0:00.00 bash                                               
 133756 root      20   0   15128   3336   3000 S   0.0   0.1   0:00.00 bash                                               
 133757 root      20   0   15128   3324   2988 S   0.0   0.1   0:00.00 bash                                               
 133800 root      20   0    4732    856    784 S   0.0   0.0   0:00.00 sleep       
 

然后按 f 键

Fields Management for window 1:Def, whose current so
   Navigate with Up/Dn, Right selects for move then 
   'd' or <Space> toggles display, 's' sets sort.  U

* PID     =    SUID    =    nDRT    =    nsPID   = 
* USER    =    SUSER   =    WCHAN   =    nsUSER  = 
* PR      =    GID     =    Flags   =    nsUTS   = 
* NI      =    GROUP   =    CGROUPS =    LXC     = 
* VIRT    =    PGRP    =    SUPGIDS =    RSan    = 
* RES     =    TTY     =    SUPGRPS =    RSfd    = 
* SHR     =    TPGID   =    TGID    =    RSlk    = 
* S       =    SID     =    OOMa    =    RSsh    = 
* %CPU    =    nTH     =    OOMs    =    CGNAME  = 
* %MEM    =    P       =    ENVIRON =    NU      = 
* TIME+   =    TIME    =    vMj     = 
* COMMAND =    SWAP    =    vMn     = 
  PPID    =    CODE    =    USED    = 
  UID     =    DATA    =    nsIPC   = 
  RUID    =    nMaj    =    nsMNT   = 
  RUSER   =    nMin    =    nsNET   = 

找到 P 后 空格 选中

Fields Management for window 1:Def, whose current so
   Navigate with Up/Dn, Right selects for move then 
   'd' or <Space> toggles display, 's' sets sort.  U

* PID     =    SUID    =    nDRT    =    nsPID   = 
* USER    =    SUSER   =    WCHAN   =    nsUSER  = 
* PR      =    GID     =    Flags   =    nsUTS   = 
* NI      =    GROUP   =    CGROUPS =    LXC     = 
* VIRT    =    PGRP    =    SUPGIDS =    RSan    = 
* RES     =    TTY     =    SUPGRPS =    RSfd    = 
* SHR     =    TPGID   =    TGID    =    RSlk    = 
* S       =    SID     =    OOMa    =    RSsh    = 
* %CPU    =    nTH     =    OOMs    =    CGNAME  = 
* %MEM    =  * P       =    ENVIRON =    NU      = 
* TIME+   =    TIME    =    vMj     = 
* COMMAND =    SWAP    =    vMn     = 
  PPID    =    CODE    =    USED    = 
  UID     =    DATA    =    nsIPC   = 
  RUID    =    nMaj    =    nsMNT   = 
  RUSER   =    nMin    =    nsNET   = 
#就会选中

q 键 返回显示结果

top - 21:22:21 up 30 min,  6 users,  load average: 0.79, 0.47, 0.29
Tasks: 241 total,   1 running, 240 sleeping,   0 stopped,   0 zombie
%Cpu(s):  1.4 us,  4.3 sy,  0.0 ni, 94.0 id,  0.0 wa,  0.2 hi,  0.2 si,  0.0 st
MiB Mem :   2807.5 total,   2056.2 free,    444.3 used,    307.0 buff/cache
MiB Swap:   2092.0 total,   2092.0 free,      0.0 used.   2197.9 avail Mem 

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND                                          P 
  41416 nginx     20   0  111724   6260   4660 S   0.0   0.2   0:00.00 nginx                                            1 
  41417 nginx     20   0  111724   5884   4536 S   0.0   0.2   0:00.00 nginx                                            2 
  75633 root      20   0       0      0      0 I   0.0   0.0   0:00.10 kworker/2:3-events                               2 
  81214 root      20   0       0      0      0 I   0.0   0.0   0:00.02 kworker/3:2-xfs-cil/dm-0                         3 
  84670 root      20   0       0      0      0 I   0.0   0.0   0:00.14 kworker/1:2-events_power_efficient               1 
  95367 root      20   0       0      0      0 I   0.0   0.0   0:00.09 kworker/u256:1-events_unbound                    2 
 111598 root      20   0       0      0      0 I   0.0   0.0   0:00.02 kworker/3:1-xfs-cil/dm-0                         3 
 113156 root      20   0       0      0      0 I   0.0   0.0   0:00.37 kworker/1:0-events_power_efficient               1 
 142043 root      20   0       0      0      0 I   0.0   0.0   0:00.01 kworker/3:0-events                               3 
 143159 root      20   0       0      0      0 I   0.0   0.0   0:00.19 kworker/1:1-events                               1 
 152990 root      20   0   61736   4584   3672 R   0.0   0.2   0:00.07 top                                              3 
 158998 root      20   0   15128   3276   2940 S   0.0   0.1   0:00.00 bash                                             0 
 158999 root      20   0   15128   3300   2968 S   0.0   0.1   0:00.00 bash                                             3 
 159000 root      20   0   15128   3320   2992 S   0.0   0.1   0:00.00 bash                                             0 

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

就是程序执行的优先级 值越小执行就先执行

[root@serevr1 ~]# head -10 /usr/local/nginx/conf/nginx.conf

user  nginx nginx;
worker_processes  3;

worker_rlimit_nofile 10240;
worker_cpu_affinity 0001 0010 0100;
worker_priority -20;  

[root@serevr1 ~]# ps -elf  | grep nginx
1 S root      191471       1  0  80   0 - 20064 -      21:28 ?        00:00:00 nginx: master process nginx
5 S nginx     191472  191471  0  60 -20 - 27931 do_epo 21:28 ?        00:00:00 nginx: worker process
5 S nginx     191473  191471  0  60 -20 - 27931 do_epo 21:28 ?        00:00:00 nginx: worker process
5 S nginx     191474  191471  0  60 -20 - 27931 do_epo 21:28 ?        00:00:00 nginx: worker process
0 S root      199092    6690  0  80   0 -  2301 -      21:29 pts/2    00:00:00 grep --color=auto nginx

事件相关的配置:event{}段中的配置参数

accept_mutex {off|on};    //master调度用户请求至各worker进程时使用的负载均衡锁;on表示能让多个worker轮流地、序列化地去响应新请求
lock_file file;    //accept_mutex用到的互斥锁锁文件路径
use [epoll | rtsig | select | poll];    //指明使用的事件模型,建议让nginx自行选择
worker_connections #;    //每个进程能够接受的最大连接数

worker_processes 的值乘以worker_connections 的值 (3*20480/2)

user  nginx nginx;
worker_processes  3;

worker_rlimit_nofile 10240;
worker_cpu_affinity 0001 0010 0100;
worker_priority -20;



#error_log  logs/error.log;
#error_log  logs/error.log  notice;
error_log  logs/error.log  error;

pid        logs/nginx.pid;


events {
    worker_connections  20480;
}

测试

[root@serevr1 ~]# yum -y install httpd-tools
[root@serevr1 ~]# ab  -n 30000 http://192.168.244.133/index.html
This is ApacheBench, Version 2.3 <$Revision: 1843412 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 192.168.244.133 (be patient)
Completed 3000 requests
Completed 6000 requests
Completed 9000 requests
Completed 12000 requests
Completed 15000 requests
Completed 18000 requests
Completed 21000 requests
Completed 24000 requests
Completed 27000 requests
Completed 30000 requests
Finished 30000 requests


Server Software:        nginx/1.20.1
Server Hostname:        192.168.244.133
Server Port:            80

Document Path:          /index.html
Document Length:        612 bytes

Concurrency Level:      1
Time taken for tests:   3.229 seconds
Complete requests:      30000
Failed requests:        0
Total transferred:      25350000 bytes
HTML transferred:       18360000 bytes
Requests per second:    9290.96 [#/sec] (mean)
Time per request:       0.108 [ms] (mean)
Time per request:       0.108 [ms] (mean, across all concurrent requests)
Transfer rate:          7666.86 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.0      0       1
Processing:     0    0   0.1      0       2
Waiting:        0    0   0.1      0       2
Total:          0    0   0.1      0       2

Percentage of the requests served within a certain time (ms)
  50%      0
  66%      0
  75%      0
  80%      0
  90%      0
  95%      0
  98%      0
  99%      1
 100%      2 (longest request)

网络连接相关的配置参数

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;
}

常需要进行调整的参数

  • worker_processes
  • worker_connections
  • worker_cpu_affinity
  • worker_priority

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";
}

编写一个

    ......
    ......
    #gzip  on;
    server {
        listen 82;
        server_name  www.yyds.com;

        location / {
            root html/test;
            index index.html;
        }
    }
    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;


在指定位置写一个index.html文件

[root@serevr1 ~]# cd  /usr/local/nginx/
[root@serevr1 nginx]# ls
client_body_temp  html        sbin
conf              logs        scgi_temp
fastcgi_temp      proxy_temp  uwsgi_temp
[root@serevr1 nginx]# cd  html/
[root@serevr1 html]# ls
50x.html  index.html
[root@serevr1 html]# mkdir test
[root@serevr1 html]# cd  test/
[root@serevr1 test]# echo "paqiu" > index.html
[root@serevr1 test]# ls
index.html

重启nginx服务

[root@serevr1 test]# nginx -s stop;nginx
[root@serevr1 test]# ss -antl
State    Recv-Q   Send-Q       Local Address:Port                     Peer Address:Port                 
LISTEN   0        128                0.0.0.0:80                            0.0.0.0:*                    
LISTEN   0        128                0.0.0.0:82                            0.0.0.0:*                    
LISTEN   0        128                0.0.0.0:22                            0.0.0.0:*                    
LISTEN   0        80                       *:3306                                *:*                    
LISTEN   0        128                   [::]:22                               [::]:*                    
[root@serevr1 test]# 
[root@serevr1 test]# curl 192.168.244.133:82
paqiu

http{}段配置指令:
server {}:定义一个虚拟主机,示例如下:

server {
  listen 80;        #IP或端口
  server_name www.idfsoft.com;    #域名
  root "/vhosts/web";             #访问html文件地址
} 

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; 默认主页面

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;

//注意:此处可用变量为nginx各模块内建变量

进入配置文件

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

        error_page  403              /403.html;  #取消注释

编写一个403网页

[root@serevr1 conf]# cat ../html/403.html 
<html>
<head>
        <title> test papap</title>
</head>
<body>
        <a href="http://www.baidu.com">百�</a>
</body>
</html>

访问

[root@serevr1 conf]# nginx -s reload
[root@serevr1 conf]# 
[root@serevr1 conf]# curl 192.168.244.133
<html>
<head>
        <title> test papap</title>
</head>
<body>
        <a href="http://www.baidu.com">百�</a>
</body>
</html>
[root@serevr1 conf]# 

log_fotmat 定义日志格式

[root@serevr1 html]# tail -f /var/log/nginx/access.log 
192.168.244.1 - - [27/Oct/2021:15:50:05 +0800] "GET / HTTP/1.1" 403 114 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36 Edg/95.0.1020.30"

[root@serevr1 ~]# vim /usr/local/nginx/conf/nginx.conf
........
........
    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;
........


192.168.244.1       $remote_addr     mac地址
第二-代表用户   - -   $remote_user      用户
[27/Oct/2021:15:50:05 +0800]   [$time_local]   时间
 GET     HTTP/1.1    $request        用什么方式去访问页面
 403    $status                     状态码
 114       $body_bytes_sent         字节
      

location

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

//功能:允许根据用户请求的URI来匹配定义的各location,匹配到时,此请求将被相应的location配置块中的配置所处理,例如做访问控制等功能

//语法:location [ 修饰符 ] pattern {......}

常用修饰符说明:

修饰符功能
=精确匹配
~正则表达式模式匹配,区分大小写
~*正则表达式模式匹配,不区分大小写
^~前缀匹配,类似于无修饰符的行为,也是以指定模块开始,不同的是,如果模式匹配,那么就停止搜索其他模式了,不支持正则表达式
@定义命名location区段,这些区段客户端不能访问,只可以由内部产生的请求来访问,如try_files或error_page等

平滑升级

1、获取现有的程序编译的参数 -V

2、获取新版本的软件包或功能包

3、将新功能或新版本进行编译

4、备份原程序

5、替换原程序

下载一功能包

github.com上搜索 nginx  echo
[root@serevr1 ~]# ls
1  anaconda-ks.cfg  echo-nginx-module-master.zip

解压

[root@serevr1 ~]# ls
1                echo-nginx-module-master
anaconda-ks.cfg  echo-nginx-module-master.zip
[root@serevr1 ~]# 

编译

[root@serevr1 bag]# ls
echo-nginx-module-master
mysql-5.7.34-linux-glibc2.12-x86_64.tar.gz
nginx-1.20.1
nginx-1.20.1.tar.gz
php-8.0.10.tar.gz

[root@serevr1 nginx-1.20.1]# pwd
/opt/lnmp/bag/nginx-1.20.1
[root@serevr1 nginx-1.20.1]# ls
CHANGES     Makefile  conf       html  src
CHANGES.ru  README    configure  man
LICENSE     auto      contrib    objs

[root@serevr1 nginx-1.20.1]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --add-module=../echo-nginx-module-master

make

[root@serevr1 nginx-1.20.1]# make
[root@serevr1 nginx-1.20.1]# ls
CHANGES     Makefile  conf       html  src
CHANGES.ru  README    configure  man
LICENSE     auto      contrib    objs
[root@serevr1 nginx-1.20.1]# cd   objs/
[root@serevr1 objs]# ls
Makefile      nginx.8             ngx_modules.o
addon         ngx_auto_config.h   src
autoconf.err  ngx_auto_headers.h
nginx         ngx_modules.c
#在/objs   多出一个nginx主程序

比较

[root@serevr1 objs]# ll nginx  /usr/local/nginx/sbin/nginx 
-rwxr-xr-x. 1 root root 6307584 Oct 27 15:35 /usr/local/nginx/sbin/nginx
-rwxr-xr-x. 1 root root 6829968 Oct 27 19:43 nginx
[root@serevr1 objs]# 

备份原控制文件(如果新程序出现问题还可以老程序即使补救)

[root@serevr1 objs]# cp /usr/local/nginx/sbin/nginx /opt/

用新程序启动

[root@serevr1 objs]# nginx -s stop;nginx -c /usr/local/nginx/conf/nginx.conf
[root@serevr1 objs]# ls
Makefile      nginx.8             ngx_modules.o
addon         ngx_auto_config.h   src
autoconf.err  ngx_auto_headers.h
nginx         ngx_modules.c

查看一下nginx进程

[root@serevr1 nginx-1.20.1]# ps  -ef  | grep nginx
root      108094       1  0 19:58 ?        00:00:00 nginx: master process nginx -c /usr/local/nginx/conf/nginx.conf
nginx     108095  108094  0 19:58 ?        00:00:00 nginx: worker process
root      111511    1780  0 19:59 pts/0    00:00:00 grep --color=auto nginx

检查语法(用新的控制文件检查)

[root@serevr1 ~]# /opt/lnmp/bag/nginx-1.20.1/objs/nginx  -t  
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful



#出现 ok 代表没问题
重新加载文件
[root@serevr1 ~]# /opt/lnmp/bag/nginx-1.20.1/objs/nginx  -s reload

覆盖文件

[root@serevr1 ~]# nginx -s stop
nginx: [emerg] unknown directive "echo" in /usr/local/nginx/conf/nginx.conf:44
[root@serevr1 ~]# /opt/lnmp/bag/nginx-1.20.1/objs/nginx  -s stop    #用新程序停掉nginx
[root@serevr1 ~]# cp /opt/lnmp/bag/nginx-1.20.1/objs/nginx  /usr/local/nginx/sbin/  #把文件覆盖
cp: overwrite '/usr/local/nginx/sbin/nginx'? y
[root@serevr1 ~]# nginx      #启动程序
[root@serevr1 ~]# ll /usr/local/nginx/sbin/
total 6672
-rwxr-xr-x. 1 root root 6829968 Oct 27 20:15 nginx  #旧城序已被新程序替代

测试新加的功能

#在配置文件里加功能

[root@serevr1 ~]# vim /usr/local/nginx/conf/nginx.conf
........

        location = /test {
            echo "hehe";
        }

        location /test {
            echo "test";
        }
        
        location / {
            root   html;
            index  index.html index.htm;
        }
........
[root@serevr1 ~]# nginx -s reload


[root@serevr1 ~]# curl http://192.168.244.133/test
hehe

在配置文里添加

[root@serevr1 ~]# vim /usr/local/nginx/conf/nginx.conf
........
        location = / {
            echo "[ configuration A ]";
        }

        location / {
            echo "[ configuration B ]";
        }

        location /documents/ {
            echo "[configuration C ]";
        }

        location ^~ /images/ {
            echo "[ configuration D ]";
        }

        location ~* \.(gif|jpg|jpeg)$ {
            echo "[configuration E ]";
        }
........

访问

[root@serevr1 ~]# curl http://192.168.244.133
[ configuration A ]
[root@serevr1 ~]# curl http://192.168.244.133/index.html
[ configuration B ]
[root@serevr1 ~]# curl http://192.168.244.133/documents/documents.html
[configuration C ]
[root@serevr1 ~]# curl http://192.168.244.133/images/1.gif
[ configuration D ]
[root@serevr1 ~]# curl http://192.168.244.133/documents/1.jpg
[configuration E ]

没有修饰符表示必须以指定模式开始,如:

        location /abc {
            echo "abc";
        }
........
#正确匹配
[root@serevr1 ~]# curl http://192.168.244.133/abc
abc
[root@serevr1 ~]# curl http://192.168.244.133/abc/
abc
[root@serevr1 ~]# curl http://192.168.244.133/abc\?
abc

表示必须与指定的模式精确匹配,如:

        location = /abc {
            echo "123";
        }

#正确匹配
[root@serevr1 ~]# curl http://192.168.244.133/abc
123
[root@serevr1 ~]# curl http://192.168.244.133/abc\?
123
#不正确匹配
[root@serevr1 ~]# curl http://192.168.244.133/abc/
abc
[root@serevr1 ~]# curl http://192.168.244.133/abc/abc/
abc

表示指定的正则表达式要区分大小写,如:


        location ~ ^/abc$ {
            echo "daxiaoxie";
        }

#正确匹配
[root@serevr1 ~]# curl http://192.168.244.133/abc?
daxiaoxie
[root@serevr1 ~]# curl http://192.168.244.133/abc
daxiaoxie
#错误匹配
[root@serevr1 ~]# curl http://192.168.244.133/abc/
abc
[root@serevr1 ~]# curl http://192.168.244.133/ABC
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
[root@serevr1 ~]# curl http://192.168.244.133/abcd
abc

表示指定的正则表达式不区分大小写,如:


        location ~* ^/abc$ {
            echo "�~M�~L��~H大�~O�~F~Y";
        }

#正确匹配
[root@serevr1 ~]# curl http://192.168.244.133/abc
不区�大小写
[root@serevr1 ~]# curl http://192.168.244.133/abc?
不区�大小写
[root@serevr1 ~]# curl http://192.168.244.133/abC
不区�大小写
#不正确匹配
[root@serevr1 ~]# curl http://192.168.244.133/abc/
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>

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

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

优先级次序如下:

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

访问控制

用于location段
allow:设定允许哪台或哪些主机访问
deny:设定禁止哪台或哪些主机访问
示例:

        location / {
            deny 192.168.244.1;  #禁止访问
            allow 192.168.244.0; #允许访问
            root html;
            index  index.html;
        }

基于用户认证

auth_basic "欢迎信息";
auth_basic_user_file "/path/to/user_auth_file"

user_auth_file内容格式为:

username:password

这里的密码为加密后的密码串,建议用htpasswd来创建此文件:

htpasswd -c -m /path/to/.user_auth_file USERNAME

生成加密文件

[root@serevr1 ~]# htpasswd -c -m   /usr/local/nginx/conf/.pass admin
New password: 
Re-type new password: 
Adding password for user admin
[root@serevr1 ~]# cat  /usr/local/nginx/conf/.pass 
admin:$apr1$Wo/HH1Mf$ZXapOQt8PqTSil9tQeAMI/

配置文件

        location /test {
            auth_basic "�~O��~O��~A�~P��~O��~X�~[��
";
            auth_basic_user_file "/usr/local/nginx/conf/.pass";
            root   html;
            index  index.html index.htm;
        }

在这里插入图片描述
在这里插入图片描述

https配置

生成私钥,生成证书签署请求并获得证书,然后在nginx.conf中配置如下内容:

server {
  listen       443 ssl;
  server_name  www.idfsoft.com;
  ssl_certificate      /etc/nginx/ssl/nginx.crt;
  ssl_certificate_key  /etc/nginx/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@serevr1 ~]# mkdir -p /etc/pki/CA 
[root@serevr1 ~]# cd  /etc/pki/CA
[root@serevr1 CA]# mkdir private
[root@serevr1 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@serevr1 CA]# 
[root@serevr1 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]:runtime
Organizational Unit Name (eg, section) []:test.runtime.com
Email Address []:1@qq.com
[root@serevr1 CA]# 
[root@serevr1 CA]# mkdir /usr/local/nginx/conf/ssl

[root@serevr1 ~]# cd  /usr/local/nginx/conf/ssl
scgi_params          ssl/
scgi_params.default 
[root@serevr1 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]:runtime
Organizational Unit Name (eg, section) []:test.runtime.com
Common Name (eg, your name or your server's hostname) []:test.runtime.com
Email Address []:1@qq.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@serevr1 ssl]# 
[root@serevr1 ssl]# ls
nginx.csr  nginx.key

[root@serevr1 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 27 14:55:37 2021 GMT
            Not After : Oct 27 14:55:37 2022 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = HB
            organizationName          = runtime
            organizationalUnitName    = test.runtime.com
            commonName                = test.runtime.com
            emailAddress              = 1@qq.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                BF:00:25:2D:F3:73:DA:76:84:DF:18:A4:26:5B:80:B6:09:1B:E8:54
            X509v3 Authority Key Identifier: 
                keyid:7C:23:9A:2F:6C:C5:AD:6B:0F:81:C9:40:BB:A3:CB:FB:7D:EE:D2:8F

Certificate is to be certified until Oct 27 14:55:37 2022 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@serevr1 ssl]# ls
nginx.crt  nginx.csr  nginx.key
[root@serevr1 ssl]# rm -rf  nginx.csr 
[root@serevr1 ssl]# ls
nginx.crt  nginx.key

配置nginx.conf文件

........
    server {
        listen       443 ssl;
        server_name  test.runtime.com;

        ssl_certificate      ssl/nginx.crt;
        ssl_certificate_key  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@serevr1 ~]# nginx -s reload
[root@serevr1 ~]# ss -antl
State    Recv-Q   Send-Q       Local Address:Port                     Peer Address:Port                 
LISTEN   0        128                0.0.0.0:443                           0.0.0.0:*                    
LISTEN   0        128                0.0.0.0:80                            0.0.0.0:*                    
LISTEN   0        128                0.0.0.0:22                            0.0.0.0:*                    
LISTEN   0        80                       *:3306                                *:*                    
LISTEN   0        128                   [::]:22                               [::]:*     

访问

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值