nginx的工作原理与nginx的配置

1、nginx的工作原理

nginx的模块直接被编译进nginx,因此属于静态编译方式。

启动nginx后,nginx的模块被自动加载,与Apache不一样,首先将模块编译为一个so文件,然后在配置文件中指定是否进行加载。

在解析配置文件时,nginx的每个模块都有可能去处理某个请求,但是同一个处理请求只能由一个模块来完成。

nginx的进程架构:
启动nginx时,会启动一个Master进程,这个进程不处理任何客户端的请求,主要用来产生worker线程,一个worker线程用来处理n个request。

nginx

下图展示了nginx模块一次常规的HTTP请求和响应的过程

nginx-http

下图展示了基本的WEB服务请求步骤

nginx-web

  • 建立连接:接收或拒绝连接请求:三次握手的过程
  • 接收请求:接收客户端请求报文中对某资源的一次请求的过程,请求报文
  • 处理请求
  • 访问资源
  • 构建响应报文
  • 发送响应报文
  • 记录日志

2、nginx的模块与工作原理

nginx由内核和模块组成。其中,内核的设计非常微小和简洁,完成的工作也非常简单,仅仅通过查找配置文件将客户端请求映射到一个location block(location是nginx配置中的一个指令,用于URL匹配),而在这个location中所配置的每个指令将会启动不同的模块去完成相应的工作。

nginx的模块从结构上分为核心模块、基础模块和第三方模块

  • HTTP模块、EVENT模块和MAIL模块等属于核心模块
  • HTTP Access模块、HTTP FastCGI模块、HTTP Proxy模块和HTTP Rewrite模块属于基本模块
  • HTTP Upstream模块、Request Hash模块、Notice模块和HTTP Access Key模块属于第三方模块

用户根据自己的需要开发的模块都属于第三方模块。正是有了如此多模块的支撑,nginx的功能才会如此强大

nginx模块从功能上分为三类,分别是:

  • Handlers(处理器模块)。此类模块直接处理请求,并进行输出内容和修改headers信息等操作。handlers处理器模块一般只能有一个
  • Filters(过滤器模块)。此类模块主要对其他处理器模块输出的内容进行修改操作,最后由nginx输出
  • Proxies(代理器模块)。就是nginx的HTTP Upstream之类的模块,这些模块主要与后端一些服务比如fastcgi等操作交互,实现服务代理和负载均衡等功能
    nginx模块分为:核心模块、事件模块、标准Http模块、可选Http模块、邮件模块、第三方模块和补丁等

nginx基本模块:所谓基本模块,指的是nginx默认的功能模块,它们提供的指令,允许你使用定义nginx基本功能的变量,在编译时不能被禁用,包括:

  • 核心模块:基本功能和指令,如进程管理和安全。常见的核心模块指令,大部分是放置在配置文件的顶部

  • 事件模块:在Nginx内配置网络使用的能力。常见的events(事件)模块指令,大部分是放置在配置文件的顶部

  • 配置模块:提供包含机制
    具体的指令,请参考nginx的官方文档

    http://nginx.org/en/docs/ngx_core_module.html

3.nginx的安装

// 创nginx建用户
[root@localhost ~]# useradd -r -M -s /sbin/nologin nginx

// 安装依赖包
[root@localhost ~]# yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++
[root@localhost ~]# yum -y groups mark install 'Development Tools'

// 创建日志存放目录
[root@JLin ~]# mkdir -p /var/log/nginx
[root@JLin ~]# chown -R nginx.nginx /var/log/nginx
[root@JLin ~]# 

// 下载nginx.tar包
[root@JLin ~]# cd /usr/src
[root@JLin src]# wget http://nginx.org/download/nginx-1.20.1.tar.gz

 // 编译安装
[root@JLin src]# tar xf nginx-1.20.1.tar.gz 
[root@JLin src]# cd nginx-1.20.1
[root@JLin 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
 [root@JLin nginx-1.20.1]# make && make install

4、nginx的配置

// 配置环境变量
[root@JLin ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH'  /etc/profile.d/nginx.sh
[root@JLin ~]# . /etc/profile.d/nginx.sh
[root@JLin ~]# 
//服务控制方式,使用nginx命令
    -t  //检查配置文件语法
    -v  //输出nginx的版本
    -c  //指定配置文件的路径
    -s  //发送服务控制信号,可选值有{stop|quit|reopen|reload}

// 启动nginx
[root@JLin ~]# nginx
[root@JLin ~]# ss -antl
State   Recv-Q  Send-Q   Local Address:Port        Peer Address:Port      Process       
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       128               [::]:22                  [::]:*    

// nginx.conf的内容分为以下几段:
main配置段:全局配置段。其中main配置段中可能包含event配置段
event {}:定义event模型工作特性
http {}:定义http协议相关的配置

5、优化性能的配置参数

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

[root@JLin ~]# cd /usr/local/nginx/conf/
[root@JLin conf]# cp nginx.conf /opt/
[root@JLin conf]# cp mime.types /opt/
[root@JLin conf]# head /opt/nginx.conf 

#user  nobody;
worker_processes  4;

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

#pid        logs/nginx.pid;

[root@JLin conf]# 
[root@JLin conf]# head /usr/local/nginx/conf/nginx.conf

#user  nobody;
worker_processes  1;

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

#pid        logs/nginx.pid;

[root@JLin ~]# ps -ef | grep nginx
[root@JLin ~]# nginx -s stop 
[root@JLin ~]# nginx
[root@JLin ~]# ps -ef | grep nginx

6、 是否以master/worker方式工作

几乎所有的产品环境下,Nginx都以“一个master进程管理多个worker进程的方式运行的”这种方式工作。

与daemon配置相同,提供master_process配置也是为了方便跟踪调试Nginx。如果用off关闭了master_process方式,就不会fork出worker子进程来处理请求,而是用master进程自身来处理请求。

[root@JLin ~]# nginx -s stop
[root@JLin ~]# nginx
[root@JLin ~]# head /opt/nginx.conf

#user  nobody;
worker_processes  4;

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

#pid        logs/nginx.pid;

[root@JLin ~]# ps -ef | grep nginx
root      223600       1  0 07:33 ?        00:00:00 nginx: master process nginx
nginx     223601  223600  0 07:33 ?        00:00:00 nginx: worker process
root      224154  188055  0 07:34 pts/0    00:00:00 grep --color=auto nginx
[root@JLin ~]# 

[root@JLin ~]# nginx -s stop;nginx -c /opt/nginx.conf
[root@JLin ~]# head /opt/nginx.conf 

#user  nobody;
worker_processes  4;

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

#pid        logs/nginx.pid;

[root@JLin ~]# ps -ef | grep nginx

root      215983  188055  0 07:29 pts/0    00:00:00 grep --color=auto nginx

7、error日志的设置

rror日志是定位Nginx问题的最佳工具,我们可以根据自己的需求妥善设置error日志的路径和级别。

/path/file参数可以是一个具体的文件,例如,默认情况下是logs/error.log文件,最好将它放到一个磁盘空间足够大的位置;/path/file也可以是/dev/null,这样就不会输出任何日志了,这也是关闭error日志的唯一手段;/path/file也可以是stderr,这样日志会输出到标准错误文件中。

level是日志的输出级别,取值范围是debug、info、notice、warn、error、crit、alert、emerg,从左至右级别依次增大。当设定为一个级别时,大于或等于该级别的日志都会被输出到/path/file文件中,小于该级别的日志则不会输出。例如,当设定为error级别时,error、crit、alert、emerg级别的日志都会输出。

如果设定的日志级别是debug,则会输出所有的日志,这样数据量会很大,需要预先确保/path/file所在磁盘有足够的磁盘空间。

注意 如果日志级别设定到debug,必须在configure时加入–with-debug配置项。

[root@JLin logs]# head /opt/nginx.conf 

#user  nobody;
worker_processes  4;

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

[root@JLin logs]# cat /usr/local/nginx/logs/error.log
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] still could not bind()
[root@JLin ~]# vim /opt/nginx.conf 
[root@JLin ~]# nginx -s stop;nginx -c /opt/nginx.conf
[root@JLin ~]# head /opt/nginx.conf

#user  nobody;
worker_processes  4;
#daemon off;
master_process on;

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

[root@JLin ~]# cat /usr/local/nginx/logs/error.log
2021/10/25 07:43:05 [notice] 240568#0: using the "epoll" event method
2021/10/25 07:43:05 [notice] 240568#0: nginx/1.20.1
2021/10/25 07:43:05 [notice] 240568#0: built by gcc 8.5.0 20210514 (Red Hat 8.5.0-3) (GCC) 
2021/10/25 07:43:05 [notice] 240568#0: OS: Linux 4.18.0-257.el8.x86_64
2021/10/25 07:43:05 [notice] 240568#0: getrlimit(RLIMIT_NOFILE): 1024:262144
2021/10/25 07:43:05 [notice] 240569#0: start worker processes
2021/10/25 07:43:05 [notice] 240569#0: start worker process 240570
2021/10/25 07:43:05 [notice] 240569#0: start worker process 240571
2021/10/25 07:43:05 [notice] 240569#0: start worker process 240572
2021/10/25 07:43:05 [notice] 240569#0: start worker process 240573
2021/10/25 07:43:07 [info] 240570#0: *1 client closed connection while waiting for request, client: 192.168.100.146, server: 0.0.0.0:80
2021/10/25 07:43:13 [info] 240570#0: *2 client closed connection while waiting for request, client: 192.168.100.146, server: 0.0.0.0:80
[root@JLin ~]# vim /opt/nginx.conf
[root@JLin ~]# head /opt/nginx.conf

#user  nobody;
worker_processes  4;
#daemon off;
master_process on;

#error_log  logs/error.log;
error_log  logs/error.log  debug;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
[root@JLin ~]# 
[root@JLin ~]# nginx -s stop;nginx -c /opt/nginx.conf
[root@JLin ~]# cat /usr/local/nginx/logs/error.log
2021/10/25 07:43:05 [notice] 240568#0: using the "epoll" event method
2021/10/25 07:43:05 [notice] 240568#0: nginx/1.20.1
2021/10/25 07:43:05 [notice] 240568#0: built by gcc 8.5.0 20210514 (Red Hat 8.5.0-3) (GCC) 
2021/10/25 07:43:05 [notice] 240568#0: OS: Linux 4.18.0-257.el8.x86_64
2021/10/25 07:43:05 [notice] 240568#0: getrlimit(RLIMIT_NOFILE): 1024:262144

8、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; stderrl syslog:server=address[,parameter=value] ; memory:sizedebug:若要使用debug级别,需要在编译nginx时使用–with-debug选项 ;info ;notice ;warn ;erro ;crit ;alert ;emerg

8.1 正常运行必备的配置参数

user USERNAME [GROUPNAME]; 指定运行worker进程的用户和组

// 用法
Syntax:	user user [group];       #语法
Default: user nobody nobody;    #默认值
Context: main                  #可以配置在那个字段中

[root@JLin ~]# vim /usr/local/nginx/conf/nginx.conf
user  nginx;					#建议手动指定用户
worker_processes  1;

pid /path/to/pid_file; 指定nginx守护进程的pid文件

// 用法
Syntax:	pid file;
Default: pid logs/nginx.pid;
Context: main

[root@JLin ~]# vim /usr/local/nginx/conf/nginx.conf
user  nginx;
worker_processes  1;
error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

pid        logs/nginx.pid;

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

// 用法
Syntax:	worker_rlimit_nofile number;
Default:	1024
Context:	main

worker_rlimit_core size; 指明所有worker进程所能够使用的总体的最大核心文件大小,保持默认即可

// 用法
Syntax:	worker_rlimit_core size;
Default:	—
Context:	main

8. .优化性能的配置参数

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

// 用法
Syntax:	worker_processes number | auto;
Default: worker_processes 1;
Context: main

[root@JLin ~]# vim /usr/local/nginx/conf/nginx.conf
#user  nobody;
worker_processes  4;    //修改nginx的worker进程数量,默认为1

[root@JLin ~]# nginx -s reload    //发送服务控制信号,重新加载配置文件
[root@JLin ~]# ps -ef | grep nginx
// worker_processes的数量*worker_connections的数量=nginx所能支持的最大并发连接数量,在实际情况最大并发数建议不超过30000

worker_cpu_affinity cpumask …; 将进程绑定到某cpu中,避免频繁刷新缓存

// 用法
Syntax:	worker_cpu_affinity cpumask ...;
        worker_cpu_affinity auto [cpumask];
Default:	—
Context:	main
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核心

特殊值 (1.9.10) 允许将工作进程自动绑定到可用的 CPU:auto
worker_processes auto;
worker_cpu_affinity auto;
可选掩码参数可用于限制可用于自动绑定的 CPU:
worker_cpu_affinity auto 01010101;
该指令仅在 FreeBSD 和 Linux 上可用。


[root@JLin ~]# nproc        #查看cpu的核心数
8
[root@JLin ~]# vim /usr/local/nginx/conf/nginx.conf
#user  nobody;
worker_processes 3 ;
worker_cpu_affinity 0001 0010 0100;    #将进程绑定在0,1,2cpu核心上运行

[root@JLin ~]# ps -ef | grep nginx

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

// 用法
Syntax:	timer_resolution interval;
Default: —
Context: main

worker_priority number; 指明worker进程的nice值

// 用法
Syntax:	worker_priority number;
Default:	
worker_priority 0;
Context:	main

[root@JLin ~]# vim /usr/local/nginx/conf/nginx.conf
#user  nobody;
worker_processes 3 ;
worker_cpu_affinity 0001 0010 0100;
worker_priority -20;

[root@JLin ~]# nginx  -s reload
[root@JLin ~]# ps -elf | grep nginx

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

accept_mutex {off|on}; master 调度用户请求至各worker进程时使用的负载均衡锁;on表示能让多个worker轮流地、序列化地去响应新请求

// 用法
Syntax:	accept_mutex on | off;
Default: accept_mutex off;
Context: events

lock_file file; accept_mutex 用到的互斥锁锁文件路径

// 用法
Syntax:	lock_file file;
Default: lock_file logs/nginx.lock;
Context: main

use [epoll | rtsig | select | poll]; 指明使用的事件模型,建议让nginx自行选择

// 用法
Syntax:	use method;
Default:	—
Context:	events

worker_connections #; 每个进程能够接受的最大连接数

// 用法
Syntax:	worker_connections number;
Default: worker_connections 512;
Context: events

[root@JLin ~]# vim /usr/local/nginx/conf/nginx.conf
#user  nobody;
worker_processes 3 ;    
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  info;

#pid        logs/nginx.pid;


events {
    worker_connections  20480;   #最大连接数乘以进程数量除以2就是最大访问并发量3000
}

8.4 网络连接相关的配置参数

keepalive_timeout number; 长连接的超时时长,默认为65s

// 用法
Syntax:	keepalive_timeout timeout [header_timeout];
Default: keepalive_timeout 65s;
Context: http, server, location

[root@JLin ~]# vim /usr/local/nginx/conf/nginx.conf
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"';
    
    #access_log  logs/access.log  main;
    
    sendfile        on;
    #tcp_nopush     on;
    keepalive_timeout  65;

keepalive_requests number; 在一个长连接上所能够允许请求的最大资源数

// 用法
Syntax:	keepalive_requests number;
Default: keepalive_requests 1000;
Context: http, server, location

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"';
    
    #access_log  logs/access.log  main;
    
    sendfile        on;
    #tcp_nopush     on;
    keepalive_timeout  65;
    keepalive_requests 1000;

keepalive_disable [msie6|safari|none]; 为指定类型的UserAgent禁用长连接

// 用法
Syntax:	keepalive_disable none | browser ...;
Default: keepalive_disable msie6;
Context: http,server,location

tcp_nodelay on|off; //是否对长连接使用TCP_NODELAY选项,为了提升用户体验,通常设为on

// 用法
Syntax:	tcp_nodelay on | off;
Default: tcp_nodelay on;
Context: http, server, location

client_header_timeout number; 读取http请求报文首部的超时时长

// 用法
Syntax:	client_header_timeout time;
Default: client_header_timeout 60s;
Context: http, server

client_body_timeout number; 读取http请求报文body部分的超时时长

// 用法
Syntax:	client_body_timeout time;
Default: client_body_timeout 60s;
Context: http, server,location

send_timeout number; 发送响应报文的超时时长

// 用法
Syntax:	send_timeout time;
Default: send_timeout 60s;
Context: http, server, location

8.5 fastcgi的相关配置参数

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

location ~ \.php$ {
            root           html;
            fastcgi_pass   127.0.0.1:9000;				#定义反向代理,此处的IP地址应该为PHP服务器的地址
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $DocumentRoot$fastcgi_script_name;
            include        fastcgi_params;
        }

8.6 常需要进行调整的参数

worker_processes        //进程数量
worker_connections      //单个进程能够打开的连接数的数量
worker_cpu_affinity     //cpu核心的绑定
worker_priority         //进程的优先级

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

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

8.8 http{}段配置指令

server {}:定义一个虚拟主机

server{
        listen       8080;
        server_name  www.csl.com;

        location / {
            root html/test;
            index index.html;
       }
    }
    
        #access_log  logs/host.access.log  main;
    
        location / {
            root   html/test;   
            index  index.html index.htm;
        }
    
        #error_page  404              /404.html;

[root@JLin ~]# cd /usr/local/nginx/html/
[root@JLin html]# ls
50x.html  index.html
[root@JLin html]# mkdir test
[root@JLin html]# ls
50x.html  index.html  test
[root@JLin html]# echo 'jjyy' test/index.html
jjyy test/index.html
[root@JLin html]# nginx -s stop;nginx


listen:指定监听的地址和端口
listen address[:port];			
listen port;

server_name NAME [...]; 后面可跟多个主机,名称可使用正则表达式或通配符,当存在多个server时,匹配顺序如下:

1. 先做精确匹配检查
2. 左侧通配符匹配检查,如*.example.com
3. 右侧通配符匹配检查,如web.*
4. 正则表达式匹配检查,如~ ^.*\.example\.com$
5. default_server

8.9 更改默认端口号以及进程数和指定特定配置文件

默认配置文件(/usr/local/nginx/conf/)nginx.conf文件内容**

[root@localhost conf]# pwd
/usr/local/nginx/conf
[root@localhost  conf]# head nginx.conf

#user  nobody;
worker_processes  1;

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

#pid        logs/nginx.pid;
.......
server {
        listen       80;
        server_name  localhost;

使用默认配置文件运行进程数如下

[root@localhost ~]# nginx
[root@localhost ~]#  ps -ef |grep nginx

将默认配置文件以及mime.types文件copy一份到/opt目录中

[root@localhost conf]# cp nginx.conf /opt/
[root@localhost conf]# cp mime.types /opt/
[root@localhost conf]# ll /opt/
-rw-r--r-- 1 root root 5231 Jun 22 01:06 mime.types
-rw-r--r-- 1 root root 2656 Jun 22 01:06 nginx.conf

[root@localhost conf]#  nginx -t -c /opt/nginx.conf 
nginx: the configuration file /opt/nginx.conf syntax is ok
nginx: configuration file /opt/nginx.conf test is successful

设置所有worker进程最大可以打开的文件数

#user  nobody;
worker_processes 5;   #改为5个进程

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

#pid        logs/nginx.pid;

server {
        listen       8080;  #更改端口号8080
        server_name  localhost;

使用nginx服务控制命令重启并指定配置文件路径

[root@localhost  opt]# nginx -s stop;nginx -c /opt/nginx.conf 
[root@localhost opt]# ps -ef | grep nginx

8.10 访问控制

注:用于location段,可以用主机地址表示,也可用网段表示,必须一起用
allow:设定允许那台或那些主机访问,多个参数间用空格隔开
deny:设定禁止那台或那些主机访问,多个参数间用空格隔开

配置访问规则

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

        location / {
            root   html;
            index  index.php index.html index.htm;
            allow  192.168.23.180/32;   #允许本机访问
            deny   all;  #配置拒绝所有访问,上面配置的允许访问规则就会失效  
        }
[root@JLin ~]# systemctl restart nginx
[root@JLin ~]# ss -anlt

使用另一台主机访问

[root@ceshi ~]# curl  192.168.23.180
curl: (7) Failed connect to 192.168.23.180:80; 拒绝连接

9、location区段

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

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

语法:location [ 修饰符 ] pattern {......}常用修饰符说明:

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

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

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


server {
        listen       8080;
        server_name  localhost;

location /test {
                echo "This is test!";
        }


[root@JLin conf]# nginx -s reload

如下内容就可正确匹配

[root@JiaL ~]# curl http://192.168.23.180:8080/test
This is test!
[root@JiaL ~]# curl http://192.168.23.180:8080/test?abc123=a1b2
This is test!
[root@JiaL ~]# curl http://192.168.23.180:8080/test/
This is test!

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

[root@JLin conf]# vim /usr/local/nginx/conf/nginx.conf
server {
        listen       8080;
        server_name  localhost;

location = /test {
                echo "This is test!";
        }
[root@JLin conf]# nginx -s reload

如下内容就可正确匹配

[root@JiaL ~]# curl http://192.168.23.180:8080/test
This is test
[root@JiaL ~]# curl http://192.168.23.180:8080/test?abc123=a1b2
This is test

如下内容则无法匹配

[root@JiaL ~]# curl http://192.168.23.180:8080/test/
<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@JiaL ~]# curl http://192.168.23.180:8080/test/test
<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@JLin conf]# vim /usr/local/nginx/conf/nginx.conf
server {
        listen       8080;
        server_name  localhost;

location = ~ ^/test {
                echo "This is test!";
[root@JLin conf]# nginx -s reload

如下内容就可正确匹配

[root@JiaL ~]# curl http://192.168.23.180:8080/test
This is test
[root@JiaL ~]# curl http://192.168.23.180:8080/test?abc123=a1b2
This is test

如下内容则无法匹配

[root@JiaL ~]# curl http://192.168.23.180:8080/test/
<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@JiaL ~]# curl http://192.168.23.180:8080/TEST/
<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@JiaL ~]# curl http://192.168.23.180:8080/testing
<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@JLin conf]# vim /usr/local/nginx/conf/nginx.conf
server {
        listen       8080;
        server_name  localhost;

location = ~* ^/test {
                echo "This is test!";
[root@JLin conf]# nginx -s reload

如下内容就可正确匹配

[root@JiaL ~]# curl http://192.168.23.180:8080/test
This is test
[root@JiaL ~]# curl http://192.168.23.180:8080/test?abc123=a1b2
This is test
[root@JiaL ~]# curl http://192.168.23.180:8080/TEST
This is test

如下内容则无法匹配

[root@JiaL ~]# curl http://192.168.23.180:8080/test/
<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@JiaL ~]# curl http://192.168.23.180:8080/testing
<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>

~:类似于无修饰符的行为,也是以指定模式开始,不同的是,如果模式匹配,则停止搜索其他模式

优先级次序
( location = 路径 ) --> ( location ^~ 路径 ) --> ( location ~ 正则 ) --> ( location ~* 正则 ) --> ( location 路径 )

查找顺序和优先级:由高到底依次为
1.带有=的精确匹配优先
2.正则表达式按照他们在配置文件中定义的顺序
3.带有^~修饰符的,开头匹配
4.带有~或~*修饰符的,如果正则表达式与URI匹配
5.没有修饰符的精确匹配

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

server {
        listen       8080;
        server_name  localhost;

        location /test {
            echo "1";
        }
        #"="优先级最高所以先注释掉
        #location = /test {
        #    echo "2";
        #}
        location ~ ^/test$ {
            echo "3";
        }
        location ~* ^/testi$ {
            echo "4";
        }
[root@JLin ~]# nginx -s reload

优先级测试

[root@JiaL ~]# curl http://192.168.23.180:8080/test
3
[root@JiaL ~]# curl http://192.168.23.180:8080/testing
1
[root@JiaL ~]# curl http://192.168.23.180:8080/TEST
4
[root@JiaL ~]# curl http://192.168.23.180:8080/test?abc123=a1b2
3
[root@JiaL ~]# curl http://192.168.23.180:8080/test/test
1

https配置

// 创建证书存放目录
[root@JLin ~]# mkdir -p /etc/nginx/ssl
[root@JLin ~]# cd /etc/nginx/ssl/

#生成密钥
[root@JLin ssl]# openssl genrsa -out test.key 2048   
Generating RSA private key, 2048 bit long modulus (2 primes)
....................................................+++++
..+++++
e is 65537 (0x010001)

// 生成证书
[root@JLin ssl]# openssl req -new -key test.key -out test.csr 
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]:ssss
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:JLin@Z.com
Email Address []:

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

[root@JLin ssl]# openssl x509 -req -days 365 -in test.csr -signkey test.key  -out test.crt
Signature ok
subject=C = CN, ST = HB, L = WH, O = ssss, CN = JLin@Z.com
Getting Private key
[root@JLin ssl]# ls
test.crt  test.csr  test.key

修改nginx配置文件

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

// 取消注释并修改域名和证书位置
    # HTTPS server
    #
    server {
        listen       443 ssl;
        server_name  www.jlin.com;

        ssl_certificate      /etc/nginx/ssl/test.crt;
        ssl_certificate_key /etc/nginx/ssl/test.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@JLin ~]# nginx -s reload
[root@JLin ~]# ss -antl

nginx.conf配置文件案例
更改默认端口号以及进程数和指定特定配置文件
源(/usr/local/nginx/conf/)nginx.conf文件内容

[root@JLin conf]# pwd
/usr/local/nginx/conf
[root@JLin conf]# head nginx.conf

#user  nobody;
worker_processes  1;

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

#pid        logs/nginx.pid;

server {
        listen       80;
        server_name  localhost;

使用源文件运行进程数如下

[root@JLin opt]# ps -ef |grep nginx

//将源文件以及mime.types文件copy一份到/opt目录中
[root@JLin conf]# cp nginx.conf /opt/
[root@JLin conf]# cp mime.types /opt/
[root@JLin opt]# ls
mime.types  nginx.conf
[root@JiaL opt]# nginx -t -c /opt/nginx.conf         //使用  -t   -s 参数测试语句
nginx: the configuration file /opt/nginx.conf syntax is ok
nginx: configuration file /opt/nginx.conf test is successful


##1 修改 worker_processes ;  参数为4
// 设置所有worker进程最大可以打开的文件数
#user  nobody;
worker_processes 4;

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

#pid        logs/nginx.pid;

server {
        listen       8080;
        server_name  localhost;

使用nginx服务控制命令重启并指定配置文件路径
​```shell
[root@JLin opt]# nginx -s stop;nginx -c /opt/nginx.conf 
[root@JLin opt]# ps -ef | grep nginx

10、访问控制

注:用于location段,可以用主机地址表示,也可用网段表示,必须一起用

allow:设定允许那台或那些主机访问,多个参数间用空格隔开
deny:设定禁止那台或那些主机访问,多个参数间用空格隔开

环境说明

主机名IP作用
JLin192.168.23.180Nginx
JiaL192.168.23.161test

在matser主机上修改nginx配置文件,将192.168.23.0网段禁止访问

[root@JLin ~]# vim /usr/local/nginx/conf/nginx.conf
        location / {
            root   html;
            index  index.php index.html index.htm;
            allow  192.168.23.180/32;
            deny   192.168.23.161/32;
        }
[root@JLin ~]# systemctl restart nginx
[root@JLin ~]# ss -anlt

在地址为192.168.23.161中访问

[root@JiaL opt]# curl 192.168.23.180:8080
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>

在 192.168.23.180中访问

[root@JLin ~]# curl 192.168.23.180:8080
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

将deny字段改为all,表示在拒绝所有主机访问

[root@JLin ~]# vim /usr/local/nginx/conf/nginx.conf
        location / {
            root   html;
            index  index.php index.html index.htm;
            allow  192.168.23.180/32;  //只允许本机访问
            deny   all;
        }
[root@JLin ~]# systemctl restart nginx
[root@JLin ~]# ss -anlt

测试

[root@JLin ~]# curl 192.168.23.180:8080
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

11、基于用户认证

auth_basic "Welcome message";
auth_basic_user_file "/path/to/user_auth_file";

user_auth_file内容格式为:

username:password

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

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

安装httpd-tools

[root@JLin ~]# yum -y install httpd-tools

必须使用不存在的用户

[root@JLin ~]# id JLin

// 生成用户认证文件
[root@JLin ~]# htpasswd -c -m /usr/local/nginx/conf/.user-auth-file JLin
New password: 
Re-type new password: 
Adding password for user JLin
[root@JLin ~]# cat /usr/local/nginx/conf/.user-auth-file 
JLin:$apr1$wxonSrbv$XbB3A8Nxr7yypySk5Kk1d.

// 创建测试文件
[root@JLin ~]# mkdir -p /usr/local/nginx/html/JLin
[root@JLin ~]# echo "welcome to JLin!" > /usr/local/nginx/html/JLin/index.html
[root@JLin ~]# vim /usr/local/nginx/conf/nginx.conf
server {
        listen       8080;
        server_name  localhost;

           location /JLin {
                root html;
                index index.html;
                auth_basic "Hello,JLin!";
                auth_basic_user_file "/usr/local/nginx/conf/.user-auth-file";

// 检测语法并重载配置文件,
[root@JLin ~]# nginx -t
[root@JLin ~]# nginx -s reload
[root@JLin ~]# ss -anlt

用于调试、定位问题
是否以守护进程方式运行Nginx
守护进程(daemon)是脱离终端并且在后台运行的进程。它脱离终端是为了避免进程执行过程中的信息在任何终端上显示,这样一来,进程也不会被任何终端所产生的信息所打断。Nginx毫无疑问是一个需要以守护进程方式运行的服务,因此,默认都是以这种方式运行的。

不过Nginx还是提供了关闭守护进程的模式,之所以提供这种模式,是为了方便跟踪调试Nginx,毕竟用gdb调试进程时最烦琐的就是如何继续跟进fork出的子进程了。

//daemon {on|off};    #是否以守护进程方式运行nginx,调试时应设置为off
[root@JLin ~]# head -5 /opt/nginx.conf 

#user  nobody;
worker_processes  4;
daemon off;
[root@JLin conf]# nginx -s stop;nginx -c /opt/nginx.conf
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

汉只只

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值