Nginx Web服务(小白的“升级打怪”成长之路)

发布于:2025-06-25 ⋅ 阅读:(15) ⋅ 点赞:(0)

目录

一、 概述

1、Nginx

1.1 Nginx 特点

1.2 Nginx 作用

1.3 Nginx工作原理

二、Nginx服务搭建

2.1 Ningx安装

2.1.1 yum安装

2.1.2 编译安装

2.2 目录结构

2.2.1 yum安装

2.2.2 编译安装

2.3 核心配置文件

2.3.1 nginx.conf配置文件详解

2.3.2 配置文件层级结构图

2.4 核心命令

三、配置案例

3.1 单站点配置

3.2 虚拟机主机头配置

3.2.1 基于IP地址

3.2.2 基于端口号

3.2.3 基于域名

四、HTTPS访问配置[自签名]

4.1 SSL简介

4.2 SSL协议介绍

4.3 传输过程

4.4 OpenSSL介绍

4.5 HTTPS 工作流程

4.6 自签名证书

4.7 nginx配置SSL

4.8 测试

五、 location配置

5.1 作用

5.2 匹配规则

5.3 匹配优先级

5.4 配置案例

六、rewrite配置

6.1 语法

6.2 可写入字段

6.3 配置案例

6.4 if 指令

6.5 autoindex

6.6 nginx配置中的常用变量

七、配置Nignx状态统计

1、下载vts模块

2、编译安装nginx

3、配置状态统计页面

4、访问状态统计页面

看到感觉有帮助的朋友,劳烦动动发财的小手给博主点个赞


一、 概述

网站常识

1)URL与URI

URI是统一资源标识符

URL 正是使用 Web 浏览器等访问Web 页面时需要输入的网页地址(客户端)

2)http

采用HTTP协议时,协议方案就是http。除此之外, 还有 ftp、mailto、telnet、file 等。

HTTP 是一种不保存状态,即无状态(stateless)协议。HTTP 协议自身不对请求和响应之间的通信状态进行保存。也就是说在 HTTP 这个级别,协议对于发送过的请求或响应都不做持久化处理。为了实现期望的保持状态功能,于是引入了 Cookie 技术。Cookie 会根据从服务器端发送的响应报文内的一个叫做 Set-Cookie的首部字段信息,通知客户端保存 Cookie。当下次客户端再往该服务器发送请求时,客户端会自动在请求报文中加入 Cookie值后发送出去。服务器端发现客户端发送过来的 Cookie 后,会去检查究竟是从哪一个客户端发来的连接请求,然后对比服务器上的记录,最后得到之前的状态信息。(Cookie 由服务器生成)

3)web

web中间件(apache nginx tomcat jboos weblogil)分为静态和动态

静态:html + css + js

动态:html + css + js (前端)

php java perl python jsp (语言环境)

数据库

4)状态码告知从服务器端返回的请求结果

状态码的类别

状态码范围 类别 原因短语
1XX Informational(信息性状态码) 接收的请求正在处理
2XX Success(成功状态码) 请求正常处理完毕
3XX Redirection(重定向状态码) 需要进行附加操作以完成请求
4XX Client Error(客户端错误状态码) 服务器无法处理请求
5XX Server Error(服务器错误状态码) 服务器处理请求出错

3xx 重定向类(常见)

状态码 状态码名称 描述 典型场景
301 Moved Permanently 资源永久重定向到新 URL,后续请求应使用新地址 网站域名变更(如 http→https)、页面永久迁移
302 Found 资源临时重定向,客户端应使用临时新地址 登录后重定向到用户主页、促销活动临时跳转
303 See Other 服务器要求客户端使用 GET 方法 重定向到新 URL(强制变更请求方法) - 表单提交后重定向到结果页面(避免重复提交) - 文件上传后跳转预览页
304 Not Modified 资源未修改,客户端可直接使用本地缓存(需配合缓存验证头) - 浏览器请求已缓存的静态资源(如图片、CSS、JS) - API 数据未更新时复用缓存

4xx 客户端错误类(常见)

状态码 状态码名称 描述 典型场景
400 Bad Request 客户端请求语法错误,服务器无法解析 参数格式错误(如邮箱格式不正确)、缺少必填字段
401 Unauthorized 请求需要身份验证(未授权) 未登录访问需要权限的页面、token 过期或无效
403 Forbidden 服务器理解请求但拒绝执行(权限不足) 未授权用户访问管理员页面、IP 被封禁
404 Not Found 请求的资源不存在 访问不存在的 URL(如拼写错误、页面已删除)
429 Too Many Requests 客户端请求频率过高,被限制访问 短时间内频繁刷新页面、API 请

5xx 服务器错误类(常见)

状态码 状态码名称 描述 典型场景
500 Internal Server Error 服务器内部错误(最常见的服务器端异常),通常由代码 bug 或配置问题导致 数据库连接失败、后台逻辑异常(如空指针)、服务器过载
502 Bad Gateway 网关错误,上游服务器(如应用服务器 / CDN)返回无效响应 反向代理服务器收到无效的后端响应、微服务间通信中断
503 Service Unavailable 服务器暂时无法处理请求(通常因过载或维护) 流量峰值导致服务器资源耗尽、系统正在进行版本升级维护
504 Gateway Timeout 网关超时,上游服务器未在规定时间内响应 后端服务处理超时(如复杂计算耗时过长)、网络链路延迟过高

1、Nginx

Nginx 是开源、高性能、高可靠的 Web服务器 和反向代理服务器,而且支持热部署,几乎可以做到 7 * 24 小时不间断运行,即使运行几个月也不需要重新启动,还能在不间断服务的情况下对软件版本进行热更新。性能是 Nginx 最重要的考量,其占用内存少、并发能力强、能支持高达 5w 个并发连接数,最重要的是, Nginx 是免费的并可以商业化,配置使用也比较简单。

1.1 Nginx 特点

  • 高并发、高性能;

  • 模块化架构使得它的扩展性非常好;

  • 异步非阻塞的事件驱动模型(epoll)这点和 Node.js 相似;

  • 相对于其它服务器来说它可以连续几个月甚至更长而不需要重启服务器使得它具有高可靠性;

  • 热部署、平滑升级;

  • 完全开源,生态繁荣。

1.2 Nginx 作用

  • http服务器。Nginx可以独立提供http服务。可做网页静态服务器。

  • 虚拟主机。可以实现在一台服务器虚拟出多个虚拟服务器。

  • 反向代理,负载均衡。当网站的访问量达到一定程度后,单台服务器不能满足用户的请求时,需要用多台服务器集群可以使用nginx做反向代理。并且多台服务器可以平均分担负载,不会应为某台服务器负载高宕机而某台服务器闲置的情况。

  • nginx 中也可以配置安全管理、比如可以使用Nginx搭建API接口网关,对每个接口服务进行拦截。

Nginx的作用

静态服务 代理服务 安全服务 流行架构
浏览器缓存 协议类型 访问控制 Nginx+PHP(Fastcgi_pass)LNMP
防资源盗用 正向代理 访问限制 Nginx+Java(Proxy_Pass)LNMT
资源分类 反向代理 流量限制 Nginx+Python(uwsgi_pass)
资源压缩 负载均衡 拦截攻击
资源缓存 代理缓存 拦截异常请求
跨域访问 动静分离 拦截SQL 注入

1.3 Nginx工作原理

二、Nginx服务搭建

2.1 Ningx安装

2.1.1 yum安装
[root@localhost ~]#yum install -y epel-release##可选
[root@localhost ~]#yum install -y nginx
##验证安装结果
[root@localhost ~]#rpm -q nginx
nginx-1.20.1-7.el7.x86_64
2.1.2 编译安装
[root@localhost ~]# ls
anaconda-ks.cfg  ceph-release-1-1.el7.noarch.rpm  nginx-1.27.3.tar.gz
[root@localhost ~]# tar xf nginx-1.27.3.tar.gz 
[root@localhost ~]# ls
anaconda-ks.cfg  ceph-release-1-1.el7.noarch.rpm  nginx-1.27.3  nginx-1.27.3.tar.gz
[root@localhost ~]# cd nginx-1.27.3
[root@localhost nginx-1.27.3]# ls
auto     CHANGES.ru          conf       contrib          html     man        SECURITY.md
CHANGES  CODE_OF_CONDUCT.md  configure  CONTRIBUTING.md  LICENSE  README.md  src
##安装依赖###
[root@localhost nginx-1.27.3]# yum install -y pcre-devel
[root@localhost nginx-1.27.3]# yum install -y zlib-devel
[root@localhost nginx-1.27.3]# ./configure --prefix=/usr/local/nginx
[root@localhost nginx-1.27.3]# make && make install
[root@localhost nginx-1.27.3]# cd /usr/local/nginx/conf/
###命令优化###
[root@localhost conf]# ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/

2.2 目录结构

2.2.1 yum安装
/etc/nginx/ ##配置文件目录
/var/lib/nginx ##临时数据文件目录
/var/log/nginx/ ##日志文件目录
/usr/share/nginx/html/ ##访问页面根目录
/etc/nginx/conf.d ##自定义配置文件目录
/etc/nginx/default.d ##默认配置文件目录
2.2.2 编译安装
/usr/local/nginx1.8/conf ##配置文件目录
/usr/local/nginx1.8/conf/conf.d ##自定义配置文件目录
/usr/local/nginx1.8/conf/default.d ##默认配置文件目录
/usr/local/nginx1.8/html ##访问页面根目录 
/usr/local/nginx1.8/logs ##日志文件目录 
/usr/local/nginx1.8/sbin ##命令存放目录

编译安装时的配置文件

分类 选项及参数 功能说明
基础信息与帮助 --help 打印帮助信息,展示所有可用编译选项说明
路径与安装配置 --prefix=PATH 设置 Nginx 安装前缀目录,后续相关路径若未单独指定,会基于此前缀设置
--sbin-path=PATH 设置 Nginx 二进制可执行文件的路径名
--modules-path=PATH 设置 Nginx 模块存放路径
--conf-path=PATH 设置 nginx.conf 配置文件的路径名
--error-log-path=PATH 设置错误日志文件的路径名
--pid-path=PATH 设置 nginx.pid(记录 Nginx 主进程 ID )文件的路径名
--lock-path=PATH 设置 nginx.lock(用于进程间同步等锁机制相关 )文件的路径名
--http-log-path=PATH 设置 HTTP 访问日志文件的路径名
--http-client-body-temp-path=PATH 设置存储 HTTP 客户端请求体临时文件的路径
--http-proxy-temp-path=PATH 设置存储 HTTP 代理临时文件的路径
--http-fastcgi-temp-path=PATH 设置存储 HTTP FastCGI 临时文件的路径
--http-uwsgi-temp-path=PATH 设置存储 HTTP uWSGI 临时文件的路径
--http-scgi-temp-path=PATH 设置存储 HTTP SCGI 临时文件的路径
用户与组配置 --user=USER 设置用于 Nginx 工作进程的非特权用户
--group=GROUP 设置用于 Nginx 工作进程的非特权用户组
构建标识与目录 --build=NAME 设置构建名称,可用于标识不同构建版本等
--builddir=DIR 设置构建目录,编译过程中相关临时文件等会存放在此目录
事件与 IO 相关 --with-select_module 启用 select 事件驱动模块(较古老,性能一般,适用于简单场景或对兼容性有要求情况 )
--without-select_module 禁用 select 事件驱动模块
--with-poll_module 启用 poll 事件驱动模块(比 select 有改进,但仍有局限 )
--without-poll_module 禁用 poll 事件驱动模块
--with-threads 启用线程池支持,有助于处理多线程相关的任务和并发场景
--with-file-aio 启用文件异步 IO(AIO )支持,提升文件读写等操作的效率,尤其对大文件或高并发 IO 场景有用
--without-quic_bpf_module 禁用 ngx_quic_bpf_module(与 QUIC 协议、BPF 相关功能 )
HTTP 模块控制 --with-http_ssl_module 启用 ngx_http_ssl_module,实现 HTTPS 功能,支持 SSL/TLS 加密传输
--with-http_v2_module 启用 ngx_http_v2_module,支持 HTTP/2 协议,提升网页等资源传输效率和性能
--with-http_v3_module 启用 ngx_http_v3_module,支持 HTTP/3 协议(实验性等情况,需结合相关环境和需求 )
--with-http_realip_module 启用 ngx_http_realip_module,用于解析真实客户端 IP(如在反向代理等场景下获取原始客户端 IP )
--with-http_addition_module 启用 ngx_http_addition_module,可对响应内容进行追加等操作
--with-http_xslt_module 启用 ngx_http_xslt_module,支持 XSLT 转换,可对 XML 内容进行样式转换等操作
--with-http_xslt_module=dynamic 以动态方式(编译为动态模块,.so 文件 )启用 ngx_http_xslt_module
--with-http_image_filter_module 启用 ngx_http_image_filter_module,支持图像过滤、处理(如缩放、裁剪等 )
--with-http_image_filter_module=dynamic 以动态方式启用 ngx_http_image_filter_module
--with-http_geoip_module 启用 ngx_http_geoip_module,结合 GeoIP 数据库实现基于客户端 IP 地理位置的功能(如限制访问等 )
--with-http_geoip_module=dynamic 以动态方式启用 ngx_http_geoip_module
--with-http_sub_module 启用 ngx_http_sub_module,可对响应内容进行替换等操作
--with-http_dav_module 启用 ngx_http_dav_module,支持 WebDAV 协议,实现文件的上传、修改等操作
--with-http_flv_module 启用 ngx_http_flv_module,支持 FLV 流媒体文件的传输和播放
--with-http_mp4_module 启用 ngx_http_mp4_module,支持 MP4 流媒体文件的传输和播放
--with-http_gunzip_module 启用 ngx_http_gunzip_module,可对压缩的响应内容进行解压(如处理 gzip 等压缩内容 )
--with-http_gzip_static_module 启用 ngx_http_gzip_static_module,支持预压缩的静态文件(如 .gz 后缀文件 )直接传输,提升效率
--with-http_auth_request_module 启用 ngx_http_auth_request_module,可实现基于外部请求的认证功能(如结合第三方认证服务 )
--with-http_random_index_module 启用 ngx_http_random_index_module,从指定目录中随机选择一个文件作为索引页返回
--with-http_secure_link_module 启用 ngx_http_secure_link_module,用于生成和验证安全链接(防止链接被恶意篡改等 )
--with-http_degradation_module 启用 ngx_http_degradation_module,在系统负载高等情况下,可对请求进行降级处理(如返回简化内容 )
--with-http_slice_module 启用 ngx_http_slice_module,支持大文件分块传输,提升下载等场景的性能和可靠性
--with-http_stub_status_module 启用 ngx_http_stub_status_module,用于获取 Nginx 自身的状态信息(如连接数、请求数等 )
--without-http_charset_module 禁用 ngx_http_charset_module,该模块用于字符集转换相关操作
--without-http_gzip_module 禁用 ngx_http_gzip_module,即不启用内置的 gzip 压缩功能(若有其他压缩方案可考虑禁用 )
--without-http_ssi_module 禁用 ngx_http_ssi_module,该模块用于处理 Server - Side Includes(SSI )功能
--without-http_userid_module 禁用 ngx_http_userid_module,用于设置和跟踪用户标识相关的功能
--without-http_access_module 禁用 ngx_http_access_module,该模块用于基于规则的访问控制(如允许 / 拒绝某些 IP 访问 )
--without-http_auth_basic_module 禁用 ngx_http_auth_basic_module,即不启用基本认证(HTTP Basic Authentication )功能
--without-http_mirror_module 禁用 ngx_http_mirror_module,该模块用于请求镜像(将请求复制到其他地址 )功能
--without-http_autoindex_module 禁用 ngx_http_autoindex_module,自动索引模块(当请求目录且无索引文件时,生成目录列表 )
--without-http_geo_module 禁用 ngx_http_geo_module,用于基于地理位置的配置和规则功能(与 geoip 模块有区别,是纯配置层面 )
--without-http_map_module 禁用 ngx_http_map_module,该模块用于创建变量映射,实现复杂的条件判断和变量赋值等操作
--without-http_split_clients_module 禁用 ngx_http_split_clients_module,用于客户端分流(如按比例将请求分发到不同后端 )功能
--without-http_referer_module 禁用 ngx_http_referer_module,用于检查和过滤 HTTP Referer 头信息相关功能
--without-http_rewrite_module 禁用 ngx_http_rewrite_module,该模块用于 URL 重写、重定向等规则配置(功能强大,慎用禁用 )
--without-http_proxy_module 禁用 ngx_http_proxy_module,即不启用 HTTP 代理功能(若 Nginx 作为纯静态服务器等可考虑 )
--without-http_fastcgi_module 禁用 ngx_http_fastcgi_module,不启用 FastCGI 相关功能(若不涉及 FastCGI 应用可禁用 )
--without-http_uwsgi_module 禁用 ngx_http_uwsgi_module,不启用 uWSGI 相关功能(若不涉及 uWSGI 应用可禁用 )
--without-http_scgi_module 禁用 ngx_http_scgi_module,不启用 SCGI 相关功能(若不涉及 SCGI 应用可禁用 )
--without-http_grpc_module 禁用 ngx_http_grpc_module,不启用 gRPC 相关功能(若不涉及 gRPC 代理等可禁用 )
--without-http_memcached_module 禁用 ngx_http_memcached_module,不启用 Memcached 相关功能(若不涉及 Memcached 交互可禁用 )
--without-http_limit_conn_module 禁用 ngx_http_limit_conn_module,不启用连接数限制功能(若无需对连接数做限制可禁用 )
--without-http_limit_req_module 禁用 ngx_http_limit_req_module,不启用请求数限制功能(若无需对请求频率等做限制可禁用 )
--without-http_empty_gif_module 禁用 ngx_http_empty_gif_module,该模块用于返回空的 GIF 图片(一些老旧功能场景可能用到 )
--without-http_browser_module 禁用 ngx_http_browser_module,用于识别客户端浏览器类型等信息的功能
--without-http_upstream_hash_module 禁用 ngx_http_upstream_hash_module,负载均衡相关的哈希模块(基于哈希策略分发请求到后端 )
--without-http_upstream_ip_hash_module 禁用 ngx_http_upstream_ip_hash_module,基于客户端 IP 哈希的负载均衡模块
--without-http_upstream_least_conn_module 禁用 ngx_http_upstream_least_conn_module,基于最少连接数的负载均衡模块
--without-http_upstream_random_module 禁用 ngx_http_upstream_random_module,基于随机策略的负载均衡模块
--without-http_upstream_keepalive_module 禁用 ngx_http_upstream_keepalive_module,用于上游服务器长连接管理的模块
--without-http_upstream_zone_module 禁用 ngx_http_upstream_zone_module,用于定义 upstream 区域(实现共享会话等高级功能 )
Perl 相关模块 --with-http_perl_module 启用 ngx_http_perl_module,支持在 Nginx 中使用 Perl 脚本进行复杂的逻辑处理
--with-http_perl_module=dynamic 以动态方式启用 ngx_http_perl_module
--with-perl_modules_path=PATH 设置 Perl 模块的路径,让 Nginx 能找到相关 Perl 模块文件
--with-perl=PATH 设置 Perl 二进制可执行文件的路径名,用于执行 Perl 相关操作
邮件模块控制 --with-mail 启用 POP3/IMAP4/SMTP 代理模块,实现邮件代理相关功能
--with-mail=dynamic 以动态方式启用邮件代理模块
--with-mail_ssl_module 启用 ngx_mail_ssl_module,为邮件代理功能添加 SSL/TLS 加密支持
--without-mail_pop3_module 禁用邮件代理中的 POP3 模块
--without-mail_imap_module 禁用邮件代理中的 IMAP 模块
--without-mail_smtp_module 禁用邮件代理中的 SMTP 模块
Stream 模块控制 --with-stream 启用 TCP/UDP 代理模块(ngx_stream_module ),实现四层协议的代理、负载均衡等功能
--with-stream=dynamic 以动态方式启用 ngx_stream_module
--with-stream_ssl_module 启用 ngx_stream_ssl_module,为 Stream 模块添加 SSL/TLS 加密支持(实现 SSL 代理等 )
--with-stream_realip_module 启用 ngx_stream_realip_module,在 Stream 场景下解析真实客户端 IP
--with-stream_geoip_module 启用 ngx_stream_geoip_module,结合 GeoIP 数据库在 Stream 场景下实现基于地理位置的功能
--with-stream_geoip_module=dynamic 以动态方式启用 ngx_stream_geoip_module
--with-stream_ssl_preread_module 启用 ngx_stream_ssl_preread_module,可在 Stream 场景下提前读取 SSL 握手信息(用于路由等 )
--without-stream_limit_conn_module 禁用 Stream 模块中的连接数限制模块
--without-stream_access_module 禁用 Stream 模块中的访问控制模块
--without-stream_geo_module 禁用 Stream 模块中基于地理位置配置的模块(类似 HTTP 模块的 geo 功能 )
--without-stream_map_module 禁用 Stream 模块中的变量映射模块
--without-stream_split_clients_module 禁用 Stream 模块中的客户端分流模块
--without-stream_return_module 禁用 Stream 模块中的返回模块(用于直接返回响应等操作 )
--without-stream_pass_module 禁用 Stream 模块中的转发模块(核心的请求转发功能,慎用禁用 )
--without-stream_set_module 禁用 Stream 模块中的变量设置模块
--without-stream_upstream_hash_module 禁用 Stream 模块中负载均衡相关的哈希模块
--without-stream_upstream_least_conn_module 禁用 Stream 模块中基于最少连接数的负载均衡模块
--without-stream_upstream_random_module 禁用 Stream 模块中基于随机策略的负载均衡模块

2.3 核心配置文件

[root@nginx1 nginx]# ls
conf.d        fastcgi.conf.default    koi-utf     mime.types.default  scgi_params          uwsgi_params.default
default.d     fastcgi_params          koi-win     nginx.conf          scgi_params.default  win-utf
fastcgi.conf  farams.default  mime.types  nginx.conf.default  uwsgi_params
​

配置文件作用表

配置文件名称 配置文件作用
fastcgi.conf 此文件包含了FastCGI相关的配置,用于与FastCGI进程通信
fastcgi.conf.default 此文件是fastcgi.conf的备份副本
fastcgi_params 此文件包含了用于FastCGI的参数配置,包括fastcgi的传输协议、请求超时时间等
fastcgi_params.default 此文件是fastcgi_params的备份副本
koi-utf 此文件包含了UTF-8编码与KOI8-R编码之间的字符转换规则,用于处理中文文件名等问题
koi-win 此文件包含了Windows系统的字符转换规则,用于处理Windows系统的文件名问题
mime.types 此文件包含了Nginx支持的MIME类型配置,用于设置相应的Content-Type头
mime.types.default 此文件是mime.types的备份副本
nginx.conf Nginx的主要配置文件,其中包含了所有全局配置和访问控制规则,作为Nginx服务器的入口文件
nginx.conf.default 此文件是nginx.conf的备份副本
scgi_params 此文件包含了用于SCGI协议的参数配置
scgi_params.default 此文件是scgi_params的备份副本
uwsgi_params 此文件包含了用于uWSGI协议的参数配置
uwsgi_params.default 此文件是uwsgi_params的备份副本
win-utf 此文件包含了Windows系统的字符转换规则,用于处理Windows系统的文件名问题
2.3.1 nginx.conf配置文件详解
##全局配置,对全局生效##
user  nobody nobody;  # 指定运行 Nginx 进程的用户为 nobody,组为nobody
pid /var/run/nginx.pid # master主进程的的pid存放在nginx.pid的文件
worker_processes  1;  # 指定 Nginx 启动的 worker 子进程数量。
#worker_processes auto; # 与当前cpu物理核心数一致
worker_rlimit_nofile 20480; # 指定 worker 子进程可以打开的最大文件句柄数。
worker_rlimit_core 50M; # 指定 worker 子进程异常终止后的 core 文件,用于记录分析问题。
working_directory /opt/nginx/tmp; # 存放目录
worker_priority -10; # 指定 worker 子进程的 nice 值,以调整运行 Nginx 的优先级,通常设定为负值,以优先调用 Nginx。
#Linux 默认进程的优先级值是120,值越小越优先;nice 定范围为 -20 到 +19 。
#应用的默认优先级值是120加上 nice 值等于它最终的值,这个值越小,优先级越高。
worker_shutdown_timeout 5s; #指定 worker 子进程优雅退出时的超时时间。
timer_resolution 100ms; #worker 子进程内部使用的计时器精度,调整时间间隔越大,系统调用越少,有利于性能提升;反之,系统调用越多,性能下降。
daemon on; # 指定 Nginx 的运行方式,前台还是后台,前台用于调试,后台用于生产。默认是on,后台运行模式。
error_log  logs/error.log;  # 错误日志文件路径
​
##events:配置影响 Nginx 服务器与用户的网络连接;##
events {
    use epoll;     # 使用epoll的I/O模型(如果你不知道Nginx该使用哪种轮询方法,会自动选择一个最适合你操作系统的)
    worker_connections  1024;  # 允许的最大并发连接数
    accept_mutex on; # 是否打开负载均衡互斥锁,默认是off关闭的,这里推荐打开
}
##http:配置代理,缓存,日志定义等绝大多数功能和第三方模块的配置;##
http {
    include       mime.types;  # 包含 MIME 类型的定义,文件扩展名与类型映射表(能处理数据的类型)
    default_type  application/octet-stream;   # 默认文件类型
    default_type  application/octet-stream;  # 默认的 MIME 类型
    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;  # 启用 TCP nopush 选项,减少网络报文段的数量
    keepalive_timeout  0;  # 禁用持久连接的超时时间
    keepalive_timeout  65;  # 保持存活连接的超时时间
    gzip  on;  # 开启 Gzip 压缩
    include /etc/nginx/conf.d/*.conf;   # 加载自定义配置项
    ##upstream:配置后端服务器具体地址,负载均衡配置不可或缺的部分。##
    upstream back_end_server{
        server 192.168.100.33:8081 #定义后端web服务器节点
    }
    ##server:配置虚拟主机的相关参数,一个 http 块中可以有多个 server 块;每个nginx相当于一个虚拟服务器的地位。##
    server {
        listen       80;  # 监听端口 80
        server_name  localhost;  # 服务器名为 localhost
        charset koi8-r;  # 字符集设置为 koi8-r
        access_log  logs/host.access.log  main;  # 主机访问日志文件及使用的日志格式
        ##location:用于配置匹配的 uri ;##
        location / {
            root   html;  # 指定静态资源目录位置,它可以写在 http 、 server 、 location 等配置中。
            index  index.html index.htm;  # 默认的索引文件
            deny 172.168.22.11;   # 禁止访问的ip地址,可以为all
            allow 172.168.33.44;# 允许访问的ip地址,可以为all
        }
        location /image {
            alias /opt/nginx/static/image/;#它也是指定静态资源目录位置,使用alias末尾一定要添加 / ,只能写在 location 中。
        }
#当用户访问 www.jx.com/image/1.png 时,实际在服务器找的路径是 /opt/nginx/static/image/1.png
        error_page  404              /404.html;  # 设置 404 错误页面的位置为 /404.html
        error_page   500 502 503 504  /50x.html;  # 将服务器错误页面重定向到 /50x.html
        location = /50x.html {
            root   html;
        }
        location ~ \.php$ {
            proxy_pass   http://127.0.0.1;  # 将 PHP 脚本代理到监听在 127.0.0.1:80 上的 Apache 服务器
        }
        location ~ \.php$ {
            root           html;  # PHP 脚本位置
            fastcgi_pass   127.0.0.1:9000;  # 向 FastCGI 服务器传递 PHP 脚本
            fastcgi_index  index.php;  # 指定 FastCGI 服务器默认的脚本文件名
            fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;  # FastCGI 参数配置
            include        fastcgi_params;  # 包含 FastCGI 相关的参数配置
        }
        location ~ /\.ht {
            deny  all;  # 阻止访问 .htaccess 文件
        }
    }
    server {
        listen       8000;  # 监听端口 8000
        listen       somename:8080;  # 监听 somename:8080
        server_name  somename  alias  another.alias;  # 服务器名设置
        location / {
            root   html;  # 根目录位置为 html 文件夹
            index  index.html index.htm;  # 默认的索引文件
        }
    }
    server {
        listen       443 ssl;  # 启动在 443 端口,并开启 SSL
        server_name  localhost;  # 服务器名为 localhost
        ssl_certificate      cert.pem;  # SSL 证书文件
        ssl_certificate_key  cert.key;  # SSL 证书的私钥文件
        ssl_session_cache    shared:SSL:1m;  # 配置 SSL 会话缓存
        ssl_session_timeout  5m;  # SSL 会话缓存的超时时间设置为 5 分钟
        ssl_ciphers  HIGH:!aNULL:!MD5;  # 配置 SSL 加密算法
        ssl_prefer_server_ciphers  on;  # 优先使用服务器端的加密套件
        location / {
            root   html;  # 根目录位置为 html 文件夹
            index  index.html index.htm;  # 默认的索引文件
        }
    }
}

nginx.conf配置

以编译安装为例

[root@localhost ~]# cd /usr/local/nginx
[root@localhost nginx]# ls
conf  html  logs  sbin
[root@localhost nginx]# cd conf
[root@localhost conf]# ls
fastcgi.conf            koi-utf             nginx.conf           uwsgi_params
fastcgi.conf.default    koi-win             nginx.conf.default   uwsgi_params.default
fastcgi_params          mime.types          scgi_params          win-utf
fastcgi_params.default  mime.types.default  scgi_params.default
###把原有的nginx.conf文件改名保留下来,里面的配置内容太简单不用###
[root@localhost conf]# mv nginx.conf nginx.conf.bak
###重新复制一个并改名为nginx.conf文件###
[root@localhost conf]# cp nginx.conf.default nginx.conf
[root@localhost conf]# ls
fastcgi.conf            koi-utf             nginx.conf          scgi_params.default
fastcgi.conf.default    koi-win             nginx.conf.bak      uwsgi_params
fastcgi_params          mime.types          nginx.conf.default  uwsgi_params.default
fastcgi_params.default  mime.types.default  scgi_params         win-utf
​
[root@localhost conf]# vim 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;     
​
events {
    worker_connections  1024;
}
​
​
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  0;
    keepalive_timeout  65;
​
    #gzip  on;
​
    server {
        listen       80;
        server_name  localhost;
​
        #charset koi8-r;
​
        #access_log  logs/host.access.log  main;
​
        location / {
            root   html;
            index  index.html index.htm;
        }
​
        #error_page  404              /404.html;
​
        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;    
        }
​
        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}
​
        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #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;
        #}
​
        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }
​
​
    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;
​
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
​
​
    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;
​
    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;
​
    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;  
​
    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;
​
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
​
} 
###更改为###
user  nobody;       ##打开,去掉注释##
worker_processes  auto;     ##改为自动##
​
error_log  logs/error.log;      ##打开,去掉注释##
error_log  logs/error.log  notice;      ##打开,去掉注释##
#error_log  logs/error.log  info;
​
pid        logs/nginx.pid;      ##打开,去掉注释##
​
​
events {
    worker_connections  1024;
}
​
​
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  0;
    keepalive_timeout  65;
​
    #gzip  on;
​
    server {
        listen       80;
        server_name  localhost;
​
        #charset koi8-r;
        charset utf8;       ##增添,并把字符集设置为 utf8##
​
        access_log  logs/access_80.log  main;       ##打开,去掉注释##
​
        location / {
            root   html;
            index  index.html index.htm;
        }    
###启动nginx服务###
[root@localhost conf]# cd ..
[root@localhost nginx]# nginx

网站访问

[root@localhost nginx]# ls
client_body_temp  conf  fastcgi_temp  html  logs  proxy_temp  sbin  scgi_temp  uwsgi_temp
[root@localhost nginx]# cd html
[root@localhost html]# ls
50x.html  index.html
[root@localhost html]# cd ../logs
[root@localhost logs]# ls
access_80.log  error.log  nginx.pid
[root@localhost logs]# cd ../conf
##编辑网站内容##
[root@localhost conf]# echo 2505 > ../html/index.html 
网站访问当前IP(192.168.58.140)显示:2505

2.3.2 配置文件层级结构图

2.4 核心命令

以yum安装的方式,nginx交给systemd管理

命令 作用
systemctl enable nginx 开机自动启动
systemctl disable nginx 关闭开机自动启动
systemctl start nginx 启动Nginx
systemctl stop nginx 停止Nginx
systemctl restart nginx 重启Nginx
systemctl reload nginx 重新加载Nginx
systemctl status nginx 查看 Nginx 运行状态
ps -elf | grep [n]ginx 查看Nginx进程,但是不会显示grep本身的进程
kill -9 pid 根据上面查看到的Nginx进程号,杀死Nginx进程,-9 表示强制结束进程
nginx -s reload 向主进程发送信号,重新加载配置文件,热重启
nginx -s reopen 重启 Nginx
nginx -s stop 快速关闭
nginx -s quit 等待工作进程处理完成后关闭
nginx -T 查看当前 Nginx 最终的配置
nginx -t 检查配置是否有问题
nginx -c configfilePath 指定配置文件启动nginx

Nginx信号

信号名 含义
stop 直接停止
quit 优雅的退出:有人在访问不会结束进程
reopen 分割日志
reload 重新加载配置文件
term 快速停止nginx进程,可能会中断现有连接,与stop信号类似。
usr1 重新打开日志文件,用于日志切割或日志重定向,与reopen信号类似。
usr2 平滑地升级nginx可执行文件。
hup 重新加载配置文件,优雅地应用新配置,与reload信号类似。
winch 当nginx以master/worker工作模式运行时,重新生成worker进程以适应新的配置。
usr3 向worker进程发送自定义信号。

以编译安装的方式,直接对nginx进行管理

nginx命令

命令选项 功能说明
-? , -h 显示此帮助信息
-v 显示版本信息并退出
-V 显示版本信息和配置选项然后退出
-t 测试配置文件并退出(检查配置语法等,配置有问题会提示)
-T 测试配置文件、 dump(输出)配置内容并退出
-q 在测试配置期间抑制非错误信息(只显示错误相关内容 )
-s signal 向主进程发送信号,可取值 stop(停止)、quit(平稳关闭,处理完当前请求再退出 )、reopen(重新打开日志文件 )、reload(重新加载配置 )
-p prefix 设置前缀路径(默认:/usr/local/nginx/ ),用于指定 nginx 相关文件(如日志、配置等)的基础路径
-e filename 设置错误日志文件(默认:logs/error.log
-c filename 设置配置文件(默认:conf/nginx.conf
-g directives 在配置文件之外设置全局指令

三、配置案例

3.1 单站点配置

安装完毕启动nginx服务即可!!

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
​
include /usr/share/nginx/modules/*.conf;
​
events {
    worker_connections 1024;
}
​
http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
​
    access_log  /var/log/nginx/access.log  main;
​
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 4096;
​
    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;
​
    include /etc/nginx/conf.d/*.conf;
​
    server {
        listen       80;
        listen       [::]:80;
        server_name  _;
        root         /usr/share/nginx/html;
​
        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
​
        error_page 404 /404.html;
        location = /404.html {
        }
​
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }
}

nginx.conf.default配置文件

user  nobody;
worker_processes  1;
​
#error_log  /var/log/nginx/error.log;
#error_log  /var/log/nginx/error.log  notice;
error_log  /var/log/nginx/error.log  info;
​
pid        /run/nginx.pid;
​
​
events {
    worker_connections  1024;
}
​
​
http {
    include       /etc/nginx/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  0;
    keepalive_timeout  65;
​
    gzip  on;
​
    server {
        listen       80;
        server_name  localhost;
​
        charset utf8;
​
        access_log  /var/log/nginx/access.log  main;
​
        location / {
            root   /usr/share/nginx/html;
            index  index.html index.htm;
        }
​
        error_page  404              /404.html;
        location = /404.html {
            root   /usr/share/nginx/html;
        }
​
        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/share/nginx/html;
        }
​
        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}
​
        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #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;
        #}
​
        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }
​
​
    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;
​
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
​
​
    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;
​
    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;
​
    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;
​
    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;
​
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
​
}

3.2 虚拟机主机头配置

3.2.1 基于IP地址
[root@localhost conf]# vim nginx.conf
user  nobody;       
worker_processes  auto;     
​
error_log  logs/error.log;      
error_log  logs/error.log  notice;      
#error_log  logs/error.log  info;
​
pid        logs/nginx.pid;      
​
​
events {
    worker_connections  1024;
}
​
​
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  0;
    keepalive_timeout  65;
​
    #gzip  on;
​
    server {
        listen       80;        ##或者将"80"改为"192.168.58.140:80",效果一样##
        server_name  localhost;
​
        #charset koi8-r;
        charset utf8;       
​
        access_log  logs/access_80.log  main;       
        location / {
            root   html;
            index  index.html index.htm;
        }    
​
##重启nginx服务##
网站访问192.168.58.140显示:2505
网站访问192.168.58.140:80显示:2505
3.2.2 基于端口号
[root@localhost conf]# vim nginx.conf
##更改此项##
server {
        listen       192.168.58.140:801;    ##更改端口号为801##
        server_name  localhost;     
​
        #charset koi8-r;
​
        #access_log  logs/80.access.log  main;
​
        location / {
            root   html/web1;
            index  index.html index.htm;
        }
[root@localhost conf]# nginx -s reload        
网站访问192.168.58.140显示:无法访问 
网站访问192.168.58.140:80显示:无法访问
网站访问192.168.58.140:801显示:2505
3.2.3 基于域名
##192.168.58.140##
[root@localhost conf]# vim nginx.conf
##更改此项##
server {
        listen       80;
        server_name  www.c2505.com;     ##加入域名##
​
        #charset koi8-r;
​
        #access_log  logs/80.access.log  main;
​
        location / {
            root   html/web1;
            index  index.html index.htm;
        }
[root@localhost conf]# nginx -s reload

为了方便,使用另外一台主机访问

##192.168.58.135##
[root@bogon ~]# vim /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.58.140 www.c2505.com
[root@bogon ~]# curl www.c2505.com
2505

增加跳转功能

基于接口跳转

[root@localhost conf]# vim nginx.conf
 ##更改此项,加入include##
 #gzip  on;
        include conf.d/*.conf;
    server {
        listen       80;    
        server_name  localhost;
​
        #charset koi8-r;
​
        #access_log  logs/host.access.log  main;
​
        location / {
            root   html;
            index  index.html index.htm;
        }
                   
[root@localhost conf]# mkdir conf.d
[root@localhost conf]# cd conf.d
[root@localhost conf.d]# touch web1.conf
[root@localhost conf.d]# vim web1.conf 
##编辑,加入这段##
server {
        listen       803;   ##更改端口号##
        server_name  localhost;
​
        #charset koi8-r;
​
        #access_log  logs/803.access.log  main;     ##更改访问日志##
​
        location / {
            root   html/web1;       ##增加一级web1##
            index  index.html index.htm;
        }
​
        error_page  404              /404.html;
​
        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
​
        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}
​
        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #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;
        #}
​
        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }
[root@localhost conf.d]# nginx -s reload
[root@localhost conf.d]# cd ../../html
[root@localhost html]# mkdir web1
[root@localhost html]# cp index.html web1/
[root@localhost html]# echo web1 > web1/index.html
网站访问当前192.168.58.140显示:2505
网站访问当前192.168.58.140:803显示:web1

基于ip跳转

[root@localhost html]# ifconfig ens33:0 192.168.58.141/24
[root@localhost html]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:0c:29:80:46:e9 brd ff:ff:ff:ff:ff:ff
    inet 192.168.58.140/24 brd 192.168.58.255 scope global noprefixroute ens33
       valid_lft forever preferred_lft forever
    inet 192.168.58.141/24 brd 192.168.58.255 scope global secondary ens33:0
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fe80:46e9/64 scope link 
       valid_lft forever preferred_lft forever
[root@localhost html]# cd ../conf/conf.d
[root@localhost conf.d]# vim web1.conf 
##更改此项##
server {
        listen       192.168.58.141:80; ##加入ip##
        server_name  localhost;
​
        #charset koi8-r;
​
        #access_log  logs/803.access.log  main;
​
        location / {
            root   html/web1;
            index  index.html index.htm;
        }
[root@localhost conf.d]# nginx -s reload
网站访问当前192.168.58.140显示:2505
网站访问当前192.168.58.141显示:web1

基于域名跳转

[root@localhost conf]# vim nginx.conf
#gzip  on;
        include conf.d/*.conf;
    server {
        listen       80;
        server_name  www.c2505.com; ##增加域名##
​
        #charset koi8-r;
        charset utf8;
​
        access_log  logs/access_80.log  main;
​
        location / {
            root   html;
            index  index.html index.htm;
        }
​
​
​
​
[root@localhost conf.d]# vim web1.conf 
##更改此项##
server {
        listen       80;
        server_name  www.c2505.com.cn;  ##加入域名##
​
        #charset koi8-r;
​
        #access_log  logs/80.access.log  main;
​
        location / {
            root   html/web1;
            index  index.html index.htm;
        }
​
[root@localhost conf.d]# nginx -s reload

为了方便,使用另外一台主机访问

##192.168.58.135##
[root@bogon ~]# vim /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.58.140 www.c2505.com
192.168.58.141 www.c2505.com.cn
[root@bogon ~]# curl www.c2505.com
2505
[root@bogon ~]# curl www.c2505.com.cn
web1

server_name 指定虚拟主机域名

域名匹配的四种写法:

精确匹配:server_name www.nginx.com ;

左侧通配:server_name *.nginx.com ;

右侧通配:server_name www.nginx.* ;

正则匹配:server_name ~^www.nginx.*$ ;

FQDN(完全限定域名):主机名.二级域.顶级域.

匹配优先级:精确匹配 > 左侧通配符匹配 > 右侧通配符匹配 > 正则表达式匹配。

server_name 配置实例:

#配置192.168.58.130为nginx服务器
[root@localhost ~]# vim /etc/nginx/nginx.conf
# 在http字段中的sever字段配置
 
# 左匹配
server {
  listen  80;
  server_name  *.nginx-test.com;
  root  /usr/share/nginx/html/nginx-test/left-match/;
  location / {
    index index.html;
  }
}
 
# 正则匹配
server {
  listen  80;
  server_name  ~^.*\.nginx-test\..*$;
  root  /usr/share/nginx/html/nginx-test/reg-match/;
  location / {
    index index.html;
  }
}
 
# 右匹配
server {
  listen  80;
  server_name  www.nginx-test.*;
  root  /usr/share/nginx/html/nginx-test/right-match/;
  location / {
    index index.html;
  }
}
 
# 精确匹配
server {
  listen  80;
  server_name  www.nginx-test.com;
  root  /usr/share/nginx/html/nginx-test/all-match/;
  location / {
    index index.html;
  }
}
#配置客户端 DNS解析。 
[root@localhost ~]# vim /etc/hosts
192.168.58.130 www.nginx-test.com
192.168.58.130 mail.nginx-test.com
192.168.58.130 www.nginx-test.org
192.168.58.130 doc.nginx-test.com
192.168.58.130 www.nginx-test.cn
192.168.58.130 fe.nginx-test.club
#访问分析
#当访问 www.jx.com 时,都可以被匹配上,因此选择优先级最高的“完全匹配”;
#当访问 mail.nginx-test.com 时,会进行“左匹配”;
#当访问 www.nginx-test.org 时,会进行“右匹配”;
#当访问 doc.nginx-test.com 时,会进行“左匹配”;
#当访问 www.nginx-test.cn 时,会进行“右匹配”;
#当访问 fe.nginx-test.club 时,会进行“正则匹配”。

四、HTTPS访问配置[自签名]

4.1 SSL简介

SSL (Secure Sockets Layer)安全套接层。是由Netscape(网景)公司于1990年开发,用于保障Word Wide Web(WWW)通讯的安全。主要任务是提供私密性,信息完整性和身份认证。1994年改版为SSLv2,1995年改版为SSLv3.

TLS(Transport Layer Security)安全传输层协议,)用于在两个通信应用程序之间提供保密性和数据完整性。该标准协议是由IETF于1999年颁布,整体来说TLS非常类似SSLv3,只是对SSLv3做了些增加和修改。

4.2 SSL协议介绍

SSL是一个不依赖于平台和应用程序的协议,位于TCP/IP协议与各种应用层协议之间,为数据通信提高安全支持。

4.3 传输过程

  • 首先发送数字证书,获取到可信的public key。

  • 通过public key发送对称秘钥,接收方用私钥解密。

  • 通信双方使用仅仅对方可知的对称秘钥进行加密传输。

4.4 OpenSSL介绍

OpenSSL是一个实现安全套接字层的加密工具包,openssl程序是一个命令行工具,用于使用OpenSSL加密库的加密函数。它可以用于:

  • 创建和管理私钥、公钥和参数

  • 公钥密码操作

  • 创建X.509证书、CSR和CRT

  • 消息摘要的计算

  • 密码加密和解密

  • SSL/TLS客户端和服务器测试

  • 处理S/MIME签名或加密邮件

  • 时间戳请求、生成和验证

4.5 HTTPS 工作流程

  • 百度服务器返回 HTTPS 使用的 CA 证书;

  • 浏览器验证 CA 证书是否为合法证书;

  • 验证通过,证书合法,生成一串随机数并使用公钥(证书中提供的)进行加密;

  • 发送公钥加密后的随机数给百度服务器;

  • 百度服务器拿到密文,通过私钥进行解密,获取到随机数(公钥加密,私钥解密,反之也可以);

  • 百度服务器把要发送给浏览器的内容,使用随机数进行加密后传输给浏览器;(对称加密)

  • 此时浏览器可以使用随机数进行解密,获取到服务器的真实传输内容。

案例:

[root@localhost ~]#openssl genrsa -out rsa1024.key 1024  ##生成私钥文件##
[root@localhost ~]#openssl req -new -key rsa1024.key -out rsa1024.csr  ##生成请求文件##
#国家
#省名
#城市
#组织名称
#组织单元名称
#主机名
#邮箱
#密码
#设置一个公司名
[root@localhost ~]#openssl x509 -req -days 365 -in rsa1024.csr -signkey rsa1024.key -out rsa1024.crt  ##生成证书##

4.6 自签名证书

[root@localhost ~]# yum install -y nginx    ##yum安装nginx服务##
#生成私钥文件(包含公钥和私钥)#
[root@localhost ~]# openssl genrsa -out nginx.key
#生成证书请求文件#
[root@localhost ~]# openssl req -new -key ./nginx.key -out nginx.csr
[root@localhost ~]# ls
anaconda-ks.cfg  ceph-release-1-1.el7.noarch.rpm  nginx.csr  nginx.key
#生成证书#
[root@localhost ~]# openssl x509 -req -days 3650 -in nginx.csr -signkey ./nginx.key -out nginx.crt
Signature ok
subject=/C=cn/ST=bj/L=bj/O=bj/OU=js/CN=c2505
Getting Private key
​
[root@localhost ~]# ls
anaconda-ks.cfg  ceph-release-1-1.el7.noarch.rpm  nginx.crt  nginx.csr  nginx.key
[root@localhost ~]# cd /etc/pki
[root@localhost pki]# ls
CA  ca-trust  java  nssdb  nss-legacy  rpm-gpg  rsyslog  tls
[root@localhost pki]# mkdir nginx
[root@localhost pki]# cd nginx
[root@localhost nginx]# ls
#将生成的私钥文件和证书请求文件及证书移动到nginx目录中#
[root@localhost nginx]# mv ~/nginx.* ./
[root@localhost nginx]# ls
nginx.crt  nginx.csr  nginx.key
​

4.7 nginx配置SSL

[root@localhost ~]# cd /etc/nginx
[root@localhost nginx]# ls
conf.d                fastcgi_params.default  nginx.conf           uwsgi_params.default
default.d             koi-utf                 nginx.conf.default   win-utf
fastcgi.conf          koi-win                 scgi_params
fastcgi.conf.default  mime.types              scgi_params.default
fastcgi_params        mime.types.default      uwsgi_params
[root@localhost nginx]# vim nginx.conf
# Settings for a TLS enabled server.
​
    server {
        listen       443 ssl http2;
        listen       [::]:443 ssl http2;
        server_name  _;
        root         /usr/share/nginx/html;
​
        ssl_certificate "/etc/pki/nginx/nginx.crt";     #设置好证书路径#
        ssl_certificate_key "/etc/pki/nginx/nginx.key";     #设置好私钥文件路径#
        ssl_session_cache shared:SSL:1m;
        ssl_session_timeout  10m;
        ssl_ciphers HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers on;
​
        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
​
        error_page 404 /404.html;
            location = /40x.html {
        }
​
        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
[root@localhost nginx]# systemctl start nginx
[root@localhost nginx]# cd /usr/share/nginx/html/
[root@localhost html]# ls
404.html  50x.html  en-US  icons  img  index.html  nginx-logo.png  poweredby.png
[root@localhost html]# echo 1111 > index.html
[root@localhost html]# cat index.html 
1111

4.8 测试

#换另一台主机测试#
[root@localhost ~]# curl -k https://192.168.58.138
1111
##成功访问到##

五、 location配置

5.1 作用

配置路径

location [ = | ~ | ~* | ^~ ] uri {
  ...
}
##在浏览器中输入的:http://www.jx.com/s?id=1&test=123,称作URL,即:统一资源定位符
##在WEB服务器中,对资源进行标识,URI,即统一资源标识符

写在server字段中。

5.2 匹配规则

  • = 精确匹配;

  • ~ 正则匹配,区分大小写;

  • ~* 正则匹配,不区分大小写;

  • ^~ 匹配到即停止搜索;

5.3 匹配优先级

= > ^~ > ~ > ~* > 不带任何字符 “/”。

5.4 配置案例

server {
  listen  80;
  server_name  www.jx.com;
 
  # 只有当访问 www.jx.com/info.html 时才会匹配到/usr/share/nginx/html/info.html
  location = /info.html {  # 必须是匹配文件
      root  /usr/share/nginx/html;
  }
 
  # 当访问 www.jx.com/1.jpg 等路径时会去 /usr/share/nginx/images/1.jpg 找对应的资源
  location ~ \.(jpeg|jpg|png|svg)$ {
    root /usr/share/nginx/html/images;
  }
 
  # 当访问 www.jx.com/bbs/ 时会匹配上 /usr/share/nginx/html/bbs/index.html
  location ^~ /bbs/ {
    root /usr/share/nginx/html;
    index index.html index.htm;
  }
}

案例及结果

[root@localhost conf]# vim nginx.conf
    server {
        listen       80;
        server_name  www.c2505.com;
​
        #charset koi8-r;
        charset utf8;
​
        access_log  logs/access_80.log  main;
​
        location / {
            root   html;
            index  index.html index.htm;
        }
        location = /a.html {
            root   html/a;
            index  index.html index.htm;
        }
​
[root@localhost conf]# nginx -s reload
[root@localhost conf]# cd ../html
[root@localhost html]# mkdir a
[root@localhost html]# cd a
[root@localhost a]# touch a.html
[root@localhost a]# echo a > a.html
网页访问192.168.58.130/a.html显示a
[root@localhost conf]# vim nginx.conf
server {
        listen       80;
        server_name  www.c2505.com;
​
        #charset koi8-r;
        charset utf8;
​
        access_log  logs/access_80.log  main;
​
        location / {
            root   html;
            index  index.html index.htm;
        }
        location /a.html {
            root   html/a;
        }
        location ~ \.(png|jpg|gif)$ {
            root   html/images;
        }
[root@localhost conf]# nginx -s reload   
[root@localhost conf]# cd ../html
[root@localhost html]# mkdir images
[root@localhost html]# cd images/
[root@localhost images]# rz
rz waiting to receive.**[root@localhost images]# ls
1.png
网页访问192.168.58.130/1.png显示1.png这张图片
[root@localhost conf]# vim nginx.conf
server {
        listen       80;
        server_name  www.c2505.com;
​
        #charset koi8-r;
        charset utf8;
​
        access_log  logs/access_80.log  main;
​
        location / {
            root   html;
            index  index.html index.htm;
        }
        location /a.html {
            root   html/a;
        }
        location ~ \.(png|jpg|gif)$ {
            root   html/images;
        }
        location ^~ /bbs/ {
            root   html;
            index  index.html index.htm;
        }
[root@localhost conf]# nginx -s reload  
[root@localhost conf]# cd ../html        
[root@localhost html]# mkdir bbs
[root@localhost html]# echo bbs > bbs/index.html
[root@localhost html]# echo bbs1 > bbs/1.html        
网页访问192.168.58.130/bbs/显示bbs
网页访问192.168.58.130/bbs/1.html显示bbs1

1、location 中的反斜线,代表后面的名字是一个文件夹名

location /test {
  ...
}
##以上写法会优先查找目录,若目录不存在则查找同名文件(直接下载文件) ,可以是目录也可以是文件
location /test/ {
  ...
}
#只能是目录

2、return

停止处理请求,直接返回响应码或重定向到其他 URL ;执行 return 指令后, location 中后续指令将不会被执行。

return code [text];
return code URL;
return URL;
 
例如:
location / {
  return 404; # 直接返回状态码
}
 
location / {
  return 404 "pages not found"; # 返回状态码 + 一段文本
}
 
location / {
  return 302 http://192.168.58.140/bbs ; # 返回状态码 + 重定向地址
}
 
location / {
  return https://www.baidu.com ; # 返回重定向地址
}
​

六、rewrite配置

根据指定正则表达式匹配规则,重写 URL 。应用场景: 新老域名的更替!!!

6.1 语法

rewrite 正则表达式 要替换的内容 [flag];

6.2 可写入字段

server、location、if

示例:

rewirte /images/(.*\.jpg)$ /pic/$1; # $1是前面括号(.*\.jpg)的反向引用

flag 可选值的含义:

  • last: 重写后的 URL 发起新请求,再次进入 server 段,重试 location 的中的匹配;

  • break :直接使用重写后的 URL ,不再匹配其它 location 中语句;

  • redirect :返回 302 临时重定向;

  • permanent :返回 301 永久重定向。

6.3 配置案例

server{
  listen 80;
  server_name www.jx.com; # 要在本地hosts文件进行配置
  root /usr/share/nginx/html;
  location /search {
    rewrite ^/(.*) https://www.baidu.com redirect;
  }
 
  location /images {
    rewrite /images/(.*) /pics/$1;
  }
 
  location /pics {
    rewrite /pics/(.*) /photos/$1;
  }
 
  location /photos {
    
  }
}
###生产环境不能使用.*,表示匹配任意!!!
#解析:
#当访问 www.jx.com/search 时,会自动帮我们重定向到 https://www.baidu.com;
#当访问 www.jx.com/images/1.jpg 时,第一步重写 URL 为 www.jx.com/pics/1.jpg ,找到 pics 的 location ,继续重写 URL 为 www.jx.com/photos/1.jpg ,找到 /photos 的 location 后,去 html/photos 目录下寻找 1.jpg 静态资源。

6.4 if 指令

语法:if (condition) {...}

可写字段:server、location

示例:

        location / {
                if ($http_user_agent ~ Chrome) {
                    rewrite /(.*) /Chrome/$1 break;
                }
                if ($http_user_agent ~ Firefox) {
                    rewrite /(.*) /Firefox/$1 break;
                }
        }
##测试192.168.115.111/index.html
set $var value; #设置变量

condition 判断条件:

  • $variable 仅为变量时,值为空或以0开头字符串都会被当做 false 处理;

  • = 或 != 相等或不等;

  • ~ 正则匹配;

  • ! ~ 非正则匹配;

  • ~* 正则匹配,不区分大小写;

  • -f 或 ! -f 检测文件存在或不存在;

  • -d 或 ! -d 检测目录存在或不存在;

  • -e 或 ! -e 检测文件、目录、符号链接等存在或不存在;

  • -x 或 ! -x 检测文件可以执行或不可执行;

配置实例

server {
  listen 8080;
  server_name www.jx.com;
  root /usr/share/nginx/html;
  location / {
    if ( $uri = "/images/" ){
      rewrite (.*) /pics/ break;
    }
  }
}
#当访问 www.jx.com/images/ 时,会进入 if 判断里面执行 rewrite 命令。

6.5 autoindex

用户请求以 / 结尾时,列出目录结构,可以用于快速搭建静态资源下载网站。

注意;不要在有混合业务的站点开启该功能,容易被攻击。

autoindex.conf 配置信息:

server {
  listen 80;
  server_name www.jx.com;
  
  location /download/ {
    root /usr/share/nginx/html;
 
    autoindex on; # 打开 autoindex,,可选参数有 on | off
    autoindex_exact_size on; # 修改为off,以KB、MB、GB显示文件大小,默认为on,以bytes显示出⽂件的确切⼤⼩
    autoindex_format html; # 以html的方式进行格式化,可选参数有 html | json | xml
    autoindex_localtime off; # 显示的⽂件时间为⽂件的服务器时间。默认为off,显示的⽂件时间为GMT时间
  }
}
#当访问 www.jx.com/download/ 时,会把服务器 /usr/share/nginx/html/download/ 路径下的文件展示出来.

6.6 nginx配置中的常用变量

变量名 含义
remote_add 客户端IP地址
remote_port 客户端端口
server_addr 服务端IP地址
Server_port 服务端端口
server_protocol 服务端协议
binary_remote_addr 二进制格式的客户端IP地址
connection TCP连接的序号,递增
connection_request TCP连接当前的请求数量
uri 请求的URL,不包含参数
request ur 请求的URL,包含参数
scheme 协议名,http或https
request metho 请求方法
request_length 全部请求的长度,包含请求行、请求头、请求体
args 全部参数字符串
arg_参数名 获取特定参数值
is_args URL中是否有参数,有的话返回?,否则返回空
query_string 与args相同
host 请求信息中的Host,如果请求中没有Host行,则在请求头中找,最后 使用nginx中设置的server_name。
http_user_agent 用户访问方式
http_referer 从哪些链接过来的请求
http_via 每经过一层代理服务器,都会添加相应的信息
http_cookie 获取用户cookie
request time 处理请求已消耗的时间
https 是否开启了https,是则返回on,否则返回空
request_filename 磁盘文件系统待访问文件的完整路径
document_root 由URI和root/alias规则生成的文件夹路径
limit_rate 返回响应时的速度上限值

配置案例

server{
  listen 8081;
  server_name www.jx.com;
  root /usr/share/nginx/html;
  location / {
    return 200 "
remote_addr: $remote_addr
remote_port: $remote_port
server_addr: $server_addr
server_port: $server_port
server_protocol: $server_protocol
binary_remote_addr: $binary_remote_addr
connection: $connection
uri: $uri
request_uri: $request_uri
scheme: $scheme
request_method: $request_method
request_length: $request_length
args: $args
arg_pid: $arg_pid
is_args: $is_args
query_string: $query_string
host: $host
http_user_agent: $http_user_agent
http_referer: $http_referer
http_via: $http_via
request_time: $request_time
https: $https
request_filename: $request_filename
document_root: $document_root
";
  }
}

当我们访问 http://www.jx.com/时,由于 Nginx 中写了 return 方法,因此浏览器会默认为我们下载一个文件,下面展示的就是下载的文件内容:

remote_addr: 192.168.115.112
remote_port: 56838
server_addr: 192.168.115.111
server_port: 8081
server_protocol: HTTP/1.1
binary_remote_addr: 茉
connection: 126
uri: /test/
request_uri: /test/?pid=121414&cid=sadasd
scheme: http
request_method: GET
request_length: 518
args: pid=121414&cid=sadasd
arg_pid: 121414
is_args: ?
query_string: pid=121414&cid=sadasd
host: var.lion-test.club
http_user_agent: Mozilla/5.0 (Windows NT 7.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0
http_referer: 
http_via: 
request_time: 0.000
https: 
request_filename: /usr/share/nginx/html/test/
document_root: /usr/share/nginx/html
​

七、配置Nignx状态统计

1、下载vts模块

https://github.com/vozlt/nginx-module-vts

2、编译安装nginx

[root@localhost ~]# rz
rz waiting to receive.**[root@localhost ~]# ls
anaconda-ks.cfg                  nginx-1.27.3         nginx-module-vts-master.zip
ceph-release-1-1.el7.noarch.rpm  nginx-1.27.3.tar.gz  shell
[root@localhost ~]# unzip nginx-module-vts-master.zip 
​
[root@localhost ~]# ls
anaconda-ks.cfg                  nginx-1.27.3.tar.gz          shell
ceph-release-1-1.el7.noarch.rpm  nginx-module-vts-master
nginx-1.27.3                     nginx-module-vts-master.zip
[root@localhost ~]# nginx -s stop
[root@localhost ~]# cd nginx-1.27.3
[root@localhost nginx-1.27.3]# ls
auto        CODE_OF_CONDUCT.md  contrib          LICENSE   objs         src
CHANGES     conf                CONTRIBUTING.md  Makefile  README.md
CHANGES.ru  configure           html             man       SECURITY.md
[root@localhost nginx-1.27.3]# ./configure --prefix=/usr/local/nginx/ --add-module=/root/nginx-module-vts-master && make
[root@localhost nginx-1.27.3]# mv /usr/local/nginx/sbin/nginx /opt/nginx.bak
[root@localhost nginx-1.27.3]# cd objs/
[root@localhost objs]# ls
addon         Makefile  nginx.8            ngx_auto_headers.h  ngx_modules.o
autoconf.err  nginx     ngx_auto_config.h  ngx_modules.c       src
[root@localhost objs]# cp ./nginx /usr/local/nginx/sbin/
[root@localhost objs]# nginx

3、配置状态统计页面

[root@localhost objs]# vim /usr/local/nginx/conf/nginx.conf
user  nginx;
worker_processes  1;
error_log  logs/error.log  info;
pid        logs/nginx.pid;
events {
    worker_connections  1024;
}
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"';
    sendfile        on;
    keepalive_timeout  65;
    gzip  on;
    ##添加如下配置###
    vhost_traffic_status_zone;
    server {
        listen       80;
        server_name  localhost;
        charset utf-8;
        access_log  logs/$server_addr.access.log  main;
        location / {
            root   html;
            index  index.html index.htm;
        }
        ##添加如下配置####
        location /status {
            vhost_traffic_status_display;
            vhost_traffic_status_display_format html;
        }
        error_page  404              /404.html;
        location = /404.html {
            root   html;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}
[root@localhost objs]# nginx -s reload

4、访问状态统计页面

http://192.168.58.130/status

看到感觉有帮助的朋友,劳烦动动发财的小手给博主点个赞


网站公告

今日签到

点亮在社区的每一天
去签到