文章目录

  • 1. nginx简介
  • 2. nginx的特性与优点
    • 2.1 nginx的特性
    • 2.2 nginx的优点
  • 3. nginx的功能及应用类别
    • 3.1 nginx的基本功能
    • 3.2 nginx的扩展功能
    • 3.3 nginx的应用类别
  • 4. nginx的模块与工作原理
  • 4.1 nginx的模块分类
    • 4.2 nginx的工作原理
  • 5. nginx的安装与配置
  • 6. web服务器请求资源的过程
  • 7.nginx的配置文件详解
    • 7.2 用于调试、定位问题的配置参数
    • 7.3 正常运行必备的配置参数
    • 7.4 优化性能的配置参数
    • 7.5 事件相关的配置:event{}段中的配置参数
    • 7.6 网络连接相关的配置参数
    • 7.7 fastcgi的相关配置参数
    • 7.8 常需要进行调整的参数
    • 7.9 nginx作为web服务器时使用的配置:http{}段的配置参数
  • 8. 错误页面配置
  • 9. 平滑升级加echo功能
  • 10. locaton配置
  • 11. 访问控制
  • 12. 用户认证
  • 13. https配置
  • 14. 开启状态界面
  • 15. rewrite:重新写入URL重定向
  • 16. if语句

1. nginx简介

nginx(发音同engine x)是一款轻量级的Web服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like协议下发行。

nginx由俄罗斯的程序设计师Igor Sysoev所开发,最初供俄国大型的入口网站及搜寻引擎Rambler使用。

第一个公开版本0.1.0发布于2004年10月4日。其将源代码以类BSD许可证的形式发布,因它的稳定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名。2011年6月1日,nginx 1.0.4发布。

nginx的特点是占有内存少,并发能力强,事实上nginx的并发能力确实在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。

2. nginx的特性与优点

2.1 nginx的特性

nginx是一个很牛的高性能Web和反向代理服务器,它具有很多非常优越的特性:

在高连接并发的情况下,nginx是Apache服务器不错的替代品,能够支持高达50000个并发连接数的响应
使用epoll and kqueue作为开发模型
nginx作为负载均衡服务器:nginx既可在内部直接支持和PHP程序对外进行服务,也可支持作为HTTP代理服务器对外进行服务
nginx采用C进行编写,不论系统资源开销还是CPU使用效率都比Perlbal要好很多

2.2 nginx的优点

  • 高并发连接:官方测试能够支撑5万并发连接,在实际生产环境中跑到2-3万并发连接数
  • 内存消耗少:在3万并发连接下,开启的10个nginx进程才消耗150M内存(15M*10=150M)
  • 配置文件非常简单:风格跟程序一样通俗易懂
  • 成本低廉:nginx为开源软件,可以免费使用。而购买F5 BIG-IP、NetScaler等硬件负载均衡交换机则需要十多万至几十万人民币
  • 支持Rewrite重写规则:能够根据域名、URL的不同,将HTTP请求分到不同的后端服务器群组
  • 内置的健康检查功能:如果Nginx Proxy后端的某台Web服务器宕机了,不会影响前端访问
  • 节省带宽:支持GZIP压缩,可以添加浏览器本地缓存的Header头
  • 稳定性高:用于反向代理,宕机的概率微乎其微
  • 模块化设计:模块可以动态编译
  • 外围支持好:文档全,二次开发和模块较多
  • 支持热部署:可以不停机重载配置文件
  • 支持事件驱动、AIO(AsyncIO,异步IO)、mmap(Memory Map,内存映射)等性能优化

3. nginx的功能及应用类别

3.1 nginx的基本功能

  • 静态资源的web服务器,能缓存打开的文件描述符
  • http、smtp、pop3协议的反向代理服务器
  • 缓存加速、负载均衡
  • 支持FastCGI(fpm,LNMP),uWSGI(Python)等
  • 模块化(非DSO机制),过滤器zip、SSI及图像的大小调整
  • 支持SSL

3.2 nginx的扩展功能

  • 基于名称和IP的虚拟主机
  • 支持keepalive
  • 支持平滑升级
  • 定制访问日志、支持使用日志缓冲区提高日志存储性能
  • 支持URL重写
  • 支持路径别名
  • 支持基于IP及用户的访问控制
  • 支持速率限制,支持并发数限制

3.3 nginx的应用类别

  • 使用nginx结合FastCGI运行PHP、JSP、Perl等程序
  • 使用nginx作反向代理、负载均衡、规则过滤
  • 使用nginx运行静态HTML网页、图片
  • nginx与其他新技术的结合应用

4. nginx的模块与工作原理

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

4.1 nginx的模块分类

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(事件)模块指令,大部分是放置在配置文件的顶部
    • 配置模块:提供包含机制

4.2 nginx的工作原理

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

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

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

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

5. nginx的安装与配置

nginx的安装见往期文章点此
文章里nginx安装后写了service文件,不写service文件也能控制nginx
但是同样需要配置环境变量

//服务控制方式,使用nginx命令-t  //检查配置文件语法-v  //输出nginx的版本-c  //指定配置文件的路径-s  //发送服务控制信号,可选值有{stop|quit|reopen|reload}//启动nginx
[root@localhost ~]# nginx
[root@localhost ~]# ss -antl
State      Recv-Q Send-Q   Local Address:Port                  Peer Address:Port
LISTEN     0      128                  *:80                               *:*
LISTEN     0      128                  *:22                               *:*
LISTEN     0      100          127.0.0.1:25                               *:*

6. web服务器请求资源的过程

  • 1 、建立连接:接收或拒绝连接请求:三次握手的过程
    提高HTTP 连接性能:

    并行连接:通过多条TCP 连接发起并发的HTTP 请求

    持久连接:keep-alive, 长连接,重用TCP 连接,以消除连接和关闭的时 延, 以事务个数和时间来决定是否关闭连接

    管道化连接:通过共享TCP 连接发起并发的HTTP 请求

    复用的连接:交替传送请求和响应报文(实验阶段,还未实现)

  • 2 、接收请求:接收客户端请求报文中对某资源的一次请求的过程,请求报文
    Web 访问响应模型(Web I/O)

    单进程I/O 模型: 启动一个进程处理用户请求,而且一次只处理一个,多个请求被串行响应,太古老了

    多进程I/O 模型 : 并行启动多个进程, 每个进程响应一个连接请求

    复用I/O 结构 :启动一个进程,同时响应N 个连接请求,连接池

    实现方法: 多线程模型和事件驱动

    多线程模型:一个进程生成N个线程,每线程响应一个连接请求

    事件驱动:一个进程处理N 个请求,Nginx

    进程:比如复制的工作,项目小组,耗资源

    线程:比如人,轻量级

    一个进程必有一个线程,一个进程可以有多个线程

    复用的多进程I/O 模型:启动M个进程,每个进程响应N个连接请求,同时 接收M*N 个请求

  • 3 、处理请求
    服务器对请求报文进行解析,并获取请求的资源及请求方法等相关信息 ,根据方法,资源,首部和可选的主体部分对请求进行处理

    元数据:请求报文首部

    HEADERS 格式 name:value

  • 4 、访问资源
    服务器获取请求报文中请求的资源web 服务器,即存放了web 资源的服务器,负责向请求者提供对方请求的静态资源,或动态运行后生成的资源
    资源放置于本地文件系统特定的路径:DocRoot 服务的根

    DocRoot —> /var/www/html

    例:/var/www/html/images/logo.jpg

    http://www.along.com/images/logo.jpg

    web 服务器资源路径映射方式:

(a) docroot

(b) alias

(c) 虚拟主机docroot

(d) 用户家目录docroot

  • 5、构建响应报文
    一旦Web 服务器识别出了资源,就执行请求方法中描述中的动作,并返回响应报文。响应报文中 ,包含有响应状态码、响应首部,如果生成了响应主体的话,还包括响应主体。

    1)响应实体:如果事务处理产生了响应主体,就将内容放在响应报文中 回送过去。响应报文中通常包括:

    描述了响应主体MIME 类型的Content-Type 首部

    描述了响应主体长度大小的Content-Length

    实际报文的主体内容

    2)URL 重定向:web 服务构建的响应并非客户端请求的资源,而是资源另外一个访问路径

    永久重定向:http://www.360buy.com —> http://www.jd.com

    临时重定向:http://www.taobao.com —> https://www.taobao.com

    3)MIME 类型:多媒体的邮件扩展

    Web 服务器要负责确定响应主体的MIME 类型。有很多配置服务器的方法可以将MIME 类型与资源管理起来

    魔法分类(扫描首部信息):Apache web 服务器可以扫描每个资源的内容,并将其与一个已知模式表,首部( 被称为魔法文件) 进行匹配,以决定每个文件的MIME 类型。这样做可能比较慢,但很方便,尤其是文件没有标准扩展名的时候

    显式分类:可以对Web 服务器进行配置,使其不考虑文件的扩展名或内容,强制特定文件或目录内容拥有某个MIME 类型,例如:php,Apache不识别,强制识别

    类型协商: 有些Web 服务器经过配置,可以以多种文档格式来存储资源。在这种情况下,可以配置Web 服务器,使其可以通过与用户的协商来决定使用哪种格式( 及相关的MIME 类型)" 最好"

  • 6 、发送响应报文
    Web 服务器通过连接发送数据时也会面临与接收数据一样的问题。服务器可能有很多条到各个客户端的连接, 有些是空闲的,有些在向服务器发送数据,还有一些在向客户端回送响应数据 。服务器 要记录连接的状态,还要特别注意对持久连接的处理。对非持久连接而言,服务器应该在发送了整条报文之后,关闭自己这一端的连接 。对持久连接来说,连接可能仍保持打开状态,在这种情况下, 服务器要 正确地计算Content-Length 首部,不然客户端就无法知道响应什么时候结束了

  • 7 、记录日志
    最后 ,当事务结束时,Web 服务器会在日志文件中添加一个条目,来描述已执行的事务

    日志类型:下一篇会详解日志各项格式的意义

    访问日志:现在愈发重要,大数据的时代

    错误日志:排错使用

7.nginx的配置文件详解

主配置文件

  • 源码安装:/usr/local/nginx/conf/nginx.conf (源码安装位置为/usr/local)

  • yum安装 :/etc/nginx/nginx.conf
    网页文件

  • 源码安装: /usr/local/nginx/html

  • yum安装: /usr/share/nginx/html/

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

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

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

  • main配置段:全局配置段。其中main配置段中可能包含event配置段
  • event {}:定义event模型工作特性
  • http{}:定义http协议相关的配置
    配置指令:要以分号结尾,语法格式如下:
derective value1 [value2 …];

支持使用变量:

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

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

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
    位置一般用的是file 文件
    级别一般默认的是error

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

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

7.4 优化性能的配置参数

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值

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

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

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

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;    //发送响应报文的超时时长

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

7.8 常需要进行调整的参数

  • worker_processes
  • worker_connections
  • worker_cpu_affinity
  • worker_priority

7.9 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; 默认主页面,与顺序有关

8. 错误页面配置

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

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

//开启错误页面
[root@localhost ]# vim /usr/local/nginx/conf/nginx.conf
48         error_page  404              /404.html;     ## 取消注释//下载提供测试页面
[root@localhost html]# wget https://fanyi.youdao.com/
--2021-10-28 10:14:30--  https://fanyi.youdao.com/
正在解析主机 fanyi.youdao.com (fanyi.youdao.com)... 103.72.47.240, 103.72.47.241
正在连接 fanyi.youdao.com (fanyi.youdao.com)|103.72.47.240|:443... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:未指定 [text/html]
正在保存至: “index.html.1”[ <=>                                                                                                                ] 22,665      --.-K/s 用时 0.004s  2021-10-28 10:14:30 (4.84 MB/s) - “index.html.1” 已保存 [22665][root@localhost html]# ls
50x.html  index.html  index.html.1
[root@localhost html]# mv index.html.1 404.html  ##改名字
[root@localhost html]# ls
404.html  50x.html  index.html
[root@localhost html]# nginx -s reload   #重新加载

// 把状态码改为200,200代表正常
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf48         error_page  404    =200          /404.html;
[root@localhost ~]# nginx -s reload

[root@localhost html]# cat /usr/local/nginx/conf/nginx.conf
21     #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '22     #                  '$status $body_bytes_sent "$http_referer" '23     #                  '"$http_user_agent" "$http_x_forwarded_for"';24 25     #access_log  logs/access.log  main; ## 访问日志26
//log_format中每一段的含义
remote_addr:对应客户端的地址
remote_user:是请求客户端请求认证的用户名,如果没有开启认证模块的话是值为空。
time_local:表示nginx服务器时间
request:表示request请求头的行
status:表示response的返回状态
body_bytes_sent:表示从服务端返回给客户端的body数据大小
http_referer:表示请求的上一级页面
http_user_agent:表示agent信息
http_x_forwarded_for:会记录每一级请求中信息//注意:此处可用变量为nginx各模块内建变量

例子

[root@localhost html]# 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;
......
[root@localhost html]# nginx -s reload
[root@localhost html]# curl 192.168.216.215 # 访问测试
[root@localhost html]# tail -f /usr/local/nginx/logs/access.log
192.168.216.233 - - [28/Oct/2021:10:32:57 +0800] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"

9. 平滑升级加echo功能

平滑升级:不能执行安装操作

  1. 获取老版本的编译参数 -V
[root@localhost html]# nginx -V
nginx version: nginx/1.20.1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC)
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --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
  1. 获取新版本或新功能的软件包
//安装git命令
[root@localhost ~]# yum -y install git//找到对应的echo模块,复制链接,将https改为git
[root@localhost ~]# git clone git://github.com/openresty/echo-nginx-module.git
正克隆到 'echo-nginx-module'...
remote: Enumerating objects: 3031, done.
remote: Counting objects: 100% (13/13), done.
remote: Compressing objects: 100% (11/11), done.
remote: Total 3031 (delta 5), reused 6 (delta 2), pack-reused 3018
接收对象中: 100% (3031/3031), 1.16 MiB | 502.00 KiB/s, done.
处理 delta 中: 100% (1629/1629), done.[root@localhost ~]# ls
anaconda-ks.cfg  echo-nginx-module  nginx.sh
  1. 对新功能或新版本的软件包进行编译
[root@localhost nginx]# cd
[root@localhost ~]# cd /usr/src
[root@localhost src]# ls
debug  kernels  nginx  nginx-1.20.1.tar.gz
[root@localhost src]# cd nginx
[root@localhost nginx]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  Makefile  man  objs  README  src
//复制原来的编译参数,最后加上模块
[root@localhost nginx]# ./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
[root@localhost nginx]# make
//比对编译后与原文件大小,不一样说明正常编译上了
[root@localhost nginx]# ll objs/nginx  /usr/local/nginx/sbin/nginx
-rwxr-xr-x 1 root root 7059904 10月 28 11:17 objs/nginx
-rwxr-xr-x 1 root root 6443544 10月 28 10:04 /usr/local/nginx/sbin/nginx
  1. 备份老程序
[root@localhost nginx]# cp /usr/local/nginx/sbin/nginx /opt/
[root@localhost nginx]# ls /opt/
backup  nginx
  1. 停掉老程序并用新程序使用老程序的配置文件进行启动
// 用echo这个模块来测试,测试location写的有没有问题
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf43         location / {44             root   html;45             index  index.php index.html index.htm;46         }47 48         location /lhj {        //在配置文件中间加上这两行,匹配到lhj就打印12349             echo "123";50         }51 52         error_page  404    =200          /404.html;
//检查语法
[root@localhost nginx]# nginx -t
nginx: [emerg] unknown directive "echo" in /usr/local/nginx/conf/nginx.conf:48
nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed[root@localhost nginx]# 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
//注释掉echo,停了再启动
[root@localhost nginx]# vim /usr/local/nginx/conf/nginx.conf
[root@localhost nginx]# nginx -s stop[root@localhost nginx]# objs/nginx -c /usr/local/nginx/conf/nginx.conf
[root@localhost nginx]# ss -antl
State       Recv-Q Send-Q                                                   Local Address:Port                                                                  Peer Address:Port
LISTEN      0      128                                                                  *:80                                                                               *:*
LISTEN      0      128                                                                  *:22                                                                               *:*
LISTEN      0      100                                                          127.0.0.1:25                                                                               *:*
LISTEN      0      128                                                                 :::22                                                                              :::*
LISTEN      0      100                                                                ::1:25                                                                              :::*
[root@localhost nginx]# 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
//重新加载
[root@localhost nginx]# objs/nginx -s reload
  1. 检验功能,若无问题即用新程序替换老程序
[root@localhost nginx]# curl http://192.168.216.215/lhj
123
[root@localhost nginx]# cp objs/nginx /usr/local/nginx/sbin/nginx
cp:是否覆盖"/usr/local/nginx/sbin/nginx"? y
[root@localhost nginx]# ll /usr/local/nginx/sbin/nginx
-rwxr-xr-x 1 root root 7059904 10月 28 11:32 /usr/local/nginx/sbin/nginx
//与前面大小一致

10. locaton配置

语法:location [ = | ~ | ~* | ^~ ] uri { … }
location @name { … }
  • location区段,通过指定模式来与客户端请求的URI相匹配
//功能:允许根据用户请求的URI来匹配定义的各location,匹配到时,此请求将被相应的location配置块中的配置所处理,例如做访问控制等功能//语法:location [ 修饰符 ] pattern {......}

常用修饰符说明:

修饰符 功能
= 精确匹配
~ 正则表达式模式匹配,区分大小写
~* 正则表达式模式匹配,不区分大小写
^~ 前缀匹配,类似于无修饰符的行为,也是以指定模块开始,不同的是,如果模式匹配,那么就停止搜索其他模式了,不支持正则表达式
@ 定义命名location区段,这些区段客户端不能访问,只可以由内部产生的请求来访问,如try_files或error_page等
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
## 注释掉以下几行43         #location / {44         #   root   html;45         #    index  index.php index.html index.htm;46         #}
## 加入以下这几行
43        # location / {44         #    root   html;45          #   index  index.html index.htm;46        # }47         location = /lhj {48             echo  "=";49         }50         location ~ /Abc {51             echo "~";52         }53         location ~* /ABC {54             echo "~*";55         }[root@localhost conf]# nginx -s reload// 检查访问
[root@localhost nginx]# objs/nginx -s reload
[root@localhost nginx]# curl 192.168.216.215/lhj
=
[root@localhost nginx]# curl 192.168.216.215/Abc
~
[root@localhost nginx]# curl 192.168.216.215/abc
~*

11. 访问控制

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

allow 192.168.1.1/32 ;
allow 192.168.2.1/32 ;
deny all;

配置访问规则

[root@localhost nginx]# vim /usr/local/nginx/conf/nginx.conflocation / {deny all;root   html;index  index.html index.htm;}[root@localhost nginx]# nginx -s reload

12. 用户认证

//下载安装包并生成密码
[root@localhost conf]# yum -y install httpd-tools[root@localhost conf]# htpasswd -c -m .pass admin     // admin是虚拟账户可随意指定,不能用来登录系统,但是可以访问nginx
New password:
Re-type new password:
Adding password for user admin[root@localhost nginx]# vim /usr/local/nginx/conf/nginx.conflocation  / {auth_basic "lhj";auth_basic_user_file ".pass";root   html;index  index.html index.htm;}
[root@localhost nginx]# nginx -s reload

13. https配置

[root@localhost ~]# cd /etc/pki/CA/
[root@localhost CA]# ls
certs  crl  newcerts  private
[root@localhost CA]# openssl genrsa -out private/cakey.pem 2048
Generating RSA private key, 2048 bit long modulus (2 primes)
...................................................................................................................................+++++
...............................................+++++
e is 65537 (0x010001)
[root@localhost 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]:hhh
Organizational Unit Name (eg, section) []:hhh
Common Name (eg, your name or your server's hostname) []:lhj
Email Address []:1@2.com[root@localhost CA]# mkdir /usr/local/nginx/conf/ssl[root@localhost CA]#  touch index.txt && echo 01 > serial
[root@localhost CA]# cd /usr/local/nginx/
[root@localhost nginx]# ls
client_body_temp  conf  fastcgi_temp  html  logs  proxy_temp  sbin  scgi_temp  uwsgi_temp
[root@localhost nginx]#  mkdir ssl
[root@localhost nginx]# cd ssl/
[root@localhost ssl]# umask 077;openssl genrsa -out nginx.key 2048
Generating RSA private key, 2048 bit long modulus (2 primes)
..............+++++
...............................................................................+++++
e is 65537 (0x010001)//客户端生成证书签署请求
[root@localhost 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]:hhh
Organizational Unit Name (eg, section) []:hhh
Common Name (eg, your name or your server's hostname) []:lhj
Email Address []:1@2.comPlease enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@localhost ssl]# ls
nginx.csr  nginx.key//CA签署客户端提交上来的证书
[root@localhost 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)ValidityNot Before: Oct 27 14:15:30 2021 GMTNot After : Oct 27 14:15:30 2022 GMTSubject:countryName               = CNstateOrProvinceName       = HBorganizationName          = hhhorganizationalUnitName    = hhhcommonName                = lhjemailAddress              = 1@2.comX509v3 extensions:X509v3 Basic Constraints: CA:FALSENetscape Comment: OpenSSL Generated CertificateX509v3 Subject Key Identifier: F8:4B:47:4C:C0:EE:67:3F:00:D9:0B:E1:8C:B3:E5:76:27:3B:51:F2X509v3 Authority Key Identifier: keyid:66:56:4E:B8:F6:1D:CD:42:9D:65:73:5A:FD:0D:09:CE:74:3C:B6:30Certificate is to be certified until Oct 27 14:15:30 2022 GMT (365 days)
Sign the certificate? [y/n]:y1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

修改nginx配置文件

//取消下面列出行的注释并修改域名和证书位置
[root@master ~]# vim /usr/local/nginx/conf/nginx.conf
109     server {110         listen       443 ssl;
111         server_name  www.test.lhj.com;
112
113         ssl_certificate      /etc/nginx/ssl/example.crt; ##修改证书路径
114         ssl_certificate_key   /etc/nginx/ssl/example.key;## 同上
115
116         ssl_session_cache    shared:SSL:1m;
117         ssl_session_timeout  5m;
118
119         ssl_ciphers  HIGH:!aNULL:!MD5;
120         ssl_prefer_server_ciphers  on;
121
122         location / {123             root   html;
124             index  index.html index.htm;
125         }
126     }
[root@nginx ~]# nginx -s reload



14. 开启状态界面

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
//添加下面3行48          location /status {49          stub_status   on;50          }
//重新加载
[root@localhost ~]# nginx -s reload


状态页面信息详解:

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

15. rewrite:重新写入URL重定向

//提供页面
[root@localhost images]# pwd
/usr/local/nginx/html/images
[root@localhost images]# ls
1.jpg


在生产过程中可能经常需要更改项目名,或者域名等,这样就访问不到我们原来的资源

[root@localhost html]# mv images imgs
[root@localhost html]# ls
50x.html  imgs  index.html

[root@localhost ~]# vim  /usr/local/nginx/conf/nginx.conf47         location /images {48             rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;    //当匹配images时自动重定向到imgs49         }[root@localhost ~]# nginx -s reload

此时刷新后变为原来的页面

[root@localhost ~]# vim  /usr/local/nginx/conf/nginx.conf47         location /images {48             rewrite ^/images/(.*)$ http://images.baidu.com;    //替换成百度的网站,当匹配到images时,自动重定向到后面的百度网站49         }[root@localhost ~]# nginx -s reload

此时刷新后变访问到了我们设置的域名

[root@localhost ~]# vim  /usr/local/nginx/conf/nginx.conf43         location / {44             root   html;45             index  index.html index.htm;46         }47         location /images {48         rewrite ^/images/(.*\.jpg)$ /imgs/$1 last;    //当匹配到images时,指向imgs因为有last,所以会继续向后匹配49         }50         51         location /imgs {52             rewrite ^/images/(.*)$ http://images.baidu.com;   // 匹配到imgs指向我们设置的域名53         }   [root@localhost ~]# nginx -s reload

16. if语句

语法:if (condition) {…}

应用场景:

server段
location段

常见的condition
变量名(变量值为空串,或者以“0”开始,则为false,其它的均为true)
以变量为操作数构成的比较表达式(可使用=,!=类似的比较操作符进行测试)
正则表达式的模式匹配操作
~:区分大小写的模式匹配检查
~:不区分大小写的模式匹配检查
!和!:对上面两种测试取反
测试指定路径为文件的可能性(-f,!-f)
测试指定路径为目录的可能性(-d,!-d)
测试文件的存在性(-e,!-e)
检查文件是否有执行权限(-x,!-x)

基于浏览器实现分离案例

if ($http_user_agent ~ Firefox) {rewrite ^(.*)$ /firefox/$1 break;
}if ($http_user_agent ~ MSIE) {rewrite ^(.*)$ /msie/$1 break;
}if ($http_user_agent ~ Chrome) {rewrite ^(.*)$ /chrome/$1 break;
}

防盗链案例

location ~* \.(jpg|gif|jpeg|png)$ {valid_referers none blocked www.idfsoft.com;if ($invalid_referer) {rewrite ^/ http://www.idfsoft.com/403.html;}
}
//将其他页面跳转过来的链接转到不存在的页面

nginx全局配置文件通解相关推荐

  1. Nginx主配置文件nginx.conf详细说明

    第3章 Nginx核心配置文件nginx.conf史上最细中文详解 3.1定义Nginx运行的用户和用户组 user nginx nginx;#改为特殊的用户和组 3.2 nginxworker进程数 ...

  2. Nginx之nginx.conf 配置文件(二)

    上一篇博客我们将 nginx 安装在 /usr/local/nginx 目录下,其默认的配置文件都放在这个目录的 conf 目录下,而主配置文件 nginx.conf 也在其中,后续对 nginx 的 ...

  3. Nginx(二)------nginx.conf 配置文件

    上一篇博客我们将 nginx 安装在 /usr/local/nginx 目录下,其默认的配置文件都放在这个目录的 conf 目录下,而主配置文件 nginx.conf 也在其中,后续对 nginx 的 ...

  4. Nginx的配置文件位置以及组成部分结构讲解

    场景 Ubuntu Server 16.04 LTS上怎样安装下载安装Nginx并启动: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/detai ...

  5. Nginx主配置文件nginx.conf中文详解

    第1章 nginx配置解释图解 第2章 Nginx核心配置文件nginx.conf史上最细中文详解 2.1 定义Nginx运行的用户和用户组 2.2 nginxworker进程数,即处理请求的进程(熟 ...

  6. nginx.conf 配置文件详解

    本文来说下nginx.conf 配置文件详解 文章目录 Nginx 配置文件概述 nginx.conf 配置文件 通用(这里是 windows 系统系 nginx1.14.2 下 nginx.conf ...

  7. 深入了解nginx.conf配置文件

    前言: Nginx是俄罗斯人编写的十分轻量级的HTTP服务器,Nginx,它的发音为"engine X",是一个高性能的HTTP和反向代理服务器,同时也是一个IMAP/POP3/S ...

  8. nginx.conf配置文件简单说明

    nginx.conf配置文件简单说明 一,nginx主要部分介绍 二,nginx通用配置文件 常用指令说明 1,main全局配置: 2,http服务器: 3,模块http_proxy: 4,模块htt ...

  9. nginx之配置文件解读及虚拟主机配置

    文章目录 一.认识配置文件 1.整体结构 2.各"块"功能 3.最详细的配置文件解释 二.配置虚拟主机 1.什么是虚拟主机? 2.虚拟主机类型 3.配置虚拟主机   如果你还没有搭 ...

最新文章

  1. 人类智慧的本质是什么?【知社视频】第118期
  2. office365加速解决方案
  3. 【OpenCV 例程200篇】30. 图像的缩放(cv2.resize)
  4. java ppt转图片 内存溢出_Java虚拟机内存及内存溢出异常
  5. json ajax查询,jQuery AJAX和JSON性能查询
  6. R包制作(千字详细图文)
  7. mac m1 obs录制麦克风+桌面音频
  8. linux编译 __stdcall,Linux下的stdcall 约定格式
  9. 如何恢复磁盘中被删除的数据
  10. error: skipping because parent directory has insecure permissions问题
  11. MySQL联合主键保存_mysql联合主键
  12. 微信小程序新版本后用户昵称变成了“微信用户“解决方法
  13. 微信小程序红包 php,微信小程序实现红包功能(后端PHP实现逻辑)
  14. (一)PCL 1.12 + VS2019 环境配置
  15. 计算机的诞生以及四个发展阶段,计算机发展历史的四个阶段
  16. 项目配置不当引发了数据泄露,人已裂开!!(建议收藏)
  17. 乔布斯往事:游戏之神卡马克眼中的“英雄和傻瓜”
  18. MVC3.0中直接在VS中浏览cshtml页面
  19. 对载荷谱进行雨流计数的几个主要步骤(以四点雨流计数为例)
  20. 6-禅宗的形成及其基本观念

热门文章

  1. AMiner推荐论文
  2. 工业品B2B平台5大要诀,降低企业采购成本捷径
  3. [战略]对空间_日志风格_日志分类_日志标记_的整体说明
  4. 黑马瑞吉外卖项目开发笔记
  5. 计算机组成原理 三种加法微操作命令
  6. 埃隆 · 马斯克、山姆 · 奥特曼和 OpenAI 的秘史
  7. 华为:活下来!或将卖掉 X86 服务器业务?
  8. 《控制论导论》读书:变异度-度量变异度
  9. 古诗词 中文 分词 自动化
  10. rrpp+ospf环网组建