当前位置: 首页 > news >正文

源码安装nginx及其配置

nginx

文章目录

    • nginx
      • 1. nginx简介
        • 1.1 nginx[官网](https://nginx.org/)
      • 2. nginx的特性与优点
        • 2.1 特性
          • 2.2.1 代理
        • 2.2 nginx的优点
        • 2.3 nginx结构
      • 3. nginx的功能及应用类别
        • 3.1 基本功能
        • 3.2 扩展功能
        • 3.3 应用类别(场景)
      • 4. nginx的模块与工作原理
        • 4.1 nginx的模块分类
        • 4.2 工作原理
      • 5. nginx的安装与配置
        • 5.1 安装
        • 5.2 nginx安装后配置
        • 5.3 配置service file
        • 5.4 查看帮助
        • 5.5 nginx参数
        • 5.6 查看日志
        • 5.7 查看nginx配置文件
      • 6. nginx的配置文件详解
        • 6.1 nginx.conf配置详解
        • 6.2 用于调试、定位问题的配置参数
        • 6.3 正常运行必备的配置参数
        • 6.4 优化性能的配置参数
        • 6.5 事件相关的配置:event{}段中的配置参数
        • 6.6 网络连接相关的配置参数
        • 6.7 fastcgi的相关配置参数
        • 6.8 常需要进行调整的参数
        • 6.9 nginx作为web服务器时使用的配置:http{}段的配置参数

1. nginx简介

1.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.1 代理
  • 正向代理为客户端服务。
    反向代理为服务器端服务。

  • 正向代理

    • 正向代理时,由客户端发送对某一个目标服务器的请求,代理服务器在中间将请求转发给该目标服务器,目标服务器将结果返回给代理服务器,代理服务器再将结果返回给客户端。
    • 使用正向代理时,客户端是需要配置代理服务的地址、端口、账号密码(如有)等才可使用的。
    • ①租客(用户)、②中介(代理服务器)、③房东(国外网站,目标服务器)
      租房子一般会很难找到房东(目标服务器),但是房东却会把房屋信息、钥匙给中介(代理服务器)。对于房东(目标服务器)来说,他可能不知道要租他房子的人(用户)是谁,他只知道中介(代理服务器)在联系他。
      引入中介(代理服务器)其实也就是因为租客(用户)无法直接联系房东(目标服务器)
  • 反向代理,nginx,负载均衡

    • 服务器根据客户端的请求,从其关系的一组或多组后端服务器(如Web服务器)上获取资源,然后再将这些资源返回给客户端,客户端只会得知代理服务器的IP地址,而不知道在代理服务器后面的服务器集群的存在。
    • 反向代理整个流程:由客户端发起对代理服务器的请求,代理服务器在中间将请求转发给某一个服务器,服务器将结果返回给代理服务器,代理服务器再将结果返回给客户端。
    • 还是租房子:假如没有中介:只有①房东、②二房东(放房东对外租房)、③租客,Web开发中就经常有这种反向代理:客户端(租客)发送请求到负载均衡服务器(二房东),负载均衡服务器(二房东)再把请求转发给一台真正的服务器(房东)来执行,再把执行结果返回给客户端(租客)
  • 透明代理

    • 透明代理也叫做内网代理(inline proxy)、拦截代理(intercepting proxy)以及强制代理(force proxy),所谓透明,即代理对客户端具有无感知性,即不需要客户端进行额外配置。
      透明代理和正向代理基本相似,甚至是透明代理可以作为正向代理的一种。
    • 透明代理技术经常作为一种备选模式存在,如在防火墙中作为策略,对部分流量进行过滤拦截;一般公司内的上网行为管理系统也是透明代理的应用。

2.2 nginx的优点

  • 高并发连接:官方测试能够支撑5万并发连接,在实际生产环境中跑到2-3万并发连接数

  • 内存消耗少:在3万并发连接下,开启的10个nginx进程才消耗150M内存(15M*10=150M)

  • 配置文件非常简单:风格跟程序一样通俗易懂

  • 成本低廉:nginx为开源软件,可以免费使用。而购买F5 BIG-IP、NetScaler等硬件负载均衡交换机则需要十多万至几十万人民币

  • 支持Rewrite重写规则:能够根据域名、URL的不同,将HTTP请求分到不同的后端服务器群组

    • 访问这个http://www.baidu.com/
      会变成这个https://www.baidu.com/
      
  • 内置的健康检查功能:如果Nginx Proxy后端的某台Web服务器宕机了,不会影响前端访问

  • 节省带宽:支持GZIP压缩,可以添加浏览器本地缓存的Header头,在网络上传输时,自动压缩,到了对面自动解压

  • 稳定性高:用于反向代理,宕机的概率微乎其微

  • 模块化设计:模块可以动态编译

    • 动态编译:编译时只编译主程序,其他的额外功能编译成模块,使用的时去加载,主程序比较小
    • 静态编译:在一开始编译将所有的功能编译到主程序中,主程序文件比较大
  • 外围支持好:文档全,二次开发和模块较多

  • 支持热部署:可以不停机重载配置文件,配置文件修改之后让它生效,不需要重启服务

  • 支持事件驱动、AIO(AsyncIO,异步IO)、mmap(Memory Map,内存映射)等性能优化

    • 同步,可以理解为在执行完一个函数或方法之后,一直等待系统返回值或消息,这时程序是出于阻塞的,只有接收到返回的值或消息后才往下执行其他的命令,同步,就是实时处理(如打电话)
    • 同步在一定程度上可以看做是单线程,这个线程请求一个方法后就待这个方法给他回复,否则他不往下执行
    • 异步,执行完函数或方法后,不必阻塞性地等待返回值或消息,只需要向系统委托一个异步过程,那么当系统接收到返回值或消息时,系统会自动触发委托的异步过程,从而完成一个完整的流程。异步,就是分时处理(如收发短信)
    • 异步在一定程度上可以看做是多线程的,请求一个方法后,就不管了,继续执行其他的方法
  • 内存映射:有一份数据在内存中放着,有多个位置需要使用,没有内存映射,同一份数据要生成多份,有的话,可以指向数据存放位置中

2.3 nginx结构

  • lamt
  • lnmt
  • lnamt
  • lnnmp
  • lnnmt

3. nginx的功能及应用类别

3.1 基本功能

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

3.2 扩展功能

  • 基于名称和IP的虚拟主机
  • 支持keepalive(长连接,保持连接)
    • 长连接:在网络中建立一个长连接,意味着建立了一个通道,这个通道可以持续传输内容
    • 没有用长连接,建立连接,传输内容,断开连接,在建立,重复的建立,断开
  • 支持平滑升级,升级过程中服务不中断
  • 定制访问日志、支持使用日志缓冲区提高日志存储性能
  • 支持URL重写
  • 支持路径别名
  • 支持基于IP及用户的访问控制,限制用户访问
  • 支持速率限制,支持并发数限制

3.3 应用类别(场景)

  • 使用nginx结合FastCGI运行PHP、JSP、Perl等程序
    • FastCGI(Fast Common Gateway Interface)快速通用网关接口,是通用网关接口CGI的改进。描述了客户端和服务器程序之间传输数据的⼀种标准。
    • JSP(全称Java Server Pages)是由[Sun Microsystems](https://baike.baidu.com/item/Sun Microsystems?fromModule=lemma_inlink)公司主导创建的一种动态网页技术标准。JSP部署于网络服务器上,可以响应客户端发送的请求,并根据请求内容动态地生成HTML、XML或其他格式文档的Web网页,然后返回给请求者。JSP技术以Java语言作为脚本语言,为用户的HTTP请求提供服务,并能与服务器上的其它Java程序共同处理复杂的业务需求。
  • 使用nginx作反向代理和负载均衡(搭配使用)、规则过滤
  • 使用nginx运行静态HTML网页、图片
  • nginx与其他新技术的结合应用

4. nginx的模块与工作原理

  • nginx由内核和模块组成。
  • 内核的设计非常微小和简洁,完成的工作也非常简单,仅仅通过查找配置文件将客户端请求映射到一个location(位置) block(location是nginx配置中的一个指令,用于URL匹配),这个location中所配置的每个指令将会启动不同的模块去完成相应的工作。
    • 这个location可以有多个,匹配到哪个,就可以定位到那个位置处理
  • URI:Uniform Resource Indentifier,统一资源标识符。用于定义全局范围内(包括但不仅限于互联网)去标记唯一的、定位一种资源访问路径的方式,或者命名方式,被称作统一资源标识符。这里的统一指的是路径格式上的统一。
  • URL:Uniform Resource Location,统一资源定位符,是URI的一个子集,用于描述在互联网上互联网资源的统一表示格式(protocol://host:port/path/to/file)

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(http协议里包头的信息)信息等操作。handlers处理器模块一般只能有一个
    • Filters(过滤器模块)。此类模块主要对其他处理器模块输出的内容进行修改操作,最后由nginx输出,取出来的信息不一定是我所需要的,将它过滤一下
    • Proxies(代理器模块)。就是nginx的HTTP Upstream之类的模块,这些模块主要与后端一些服务比如fastcgi等操作交互,实现服务代理和负载均衡等功能
  • nginx模块分为:核心模块、事件模块、标准Http模块、可选Http模块、邮件模块、第三方模块和补丁等

    • nginx基本模块:所谓基本模块,指的是nginx默认的功能模块,它们提供的指令,允许你使用定义nginx基本功能的变量,在编译时不能被禁用,包括:
      • 核心模块:基本功能和指令,如进程管理和安全。常见的核心模块指令,大部分是放置在配置文件的顶部(顶部,在主配置文件中的最左侧)
      • 事件模块:在Nginx内配置网络使用的能力。常见的events(事件)模块指令,大部分是放置在配置文件的顶部
      • 配置模块:提供包含机制
  • nginx官方文档

4.2 工作原理

  • nginx的模块直接被编译进nginx,属于静态编译方式。
  • 启动nginx后,nginx的模块被自动加载,与Apache不一样,首先将模块编译为一个so文件,然后在配置文件中指定是否进行加载。
  • 在解析配置文件时,nginx的每个模块都有可能去处理某个请求,但是同一个处理请求只能由一个模块来完成。
  • nginx的进程架构:
    启动nginx时,会启动一个Master进程,这个进程不处理任何客户端的请求,主要用来产生worker线程,一个worker线程用来处理n个request

img

  • 用户先找到nginx,nginx交给master,master生成很多worker,worker包括很多模块,核心功能
    
    worker查看信息是本地处理还是其他人处理。如果是本地处理直接找到硬盘缓存下来处理,下次再请求静态资源直接将缓存资源给他
    如果是动态的就通过fastcgi交给应用服务器,应用服务器处理完返还给他
    本地缓存没有mencache强大,所以放入mencache中,如果有请求,直接查看mencache缓存
    
    mencache没有持久化
    
    中间的master和proxy是nginx,前端,做负载均衡,worker首先查看资源是动态的还是静态的,是静态的用http交给web server直接处理,处理完成后
    
    
    webserver 后端做rs
    
  • nginx模块一次常规的HTTP请求和响应的过程

img

  • 用户通过http发出请求,nginx内核建立一个handlers处理器模块,用模块处理,处理完之后,用过滤器进行过滤,得到结果响应用户
    
    处理器模块还会用到代理模块
    
  • 基本的WEB服务请求步骤:

img

  • 通过用户的浏览器跟服务器的nginx建立连接,建立连接用的是tcp/ip协议
    
    建立连接通道之后可以发送请求,nginx收到请求,处理请求,访问资源(资源存放在硬盘上),取出资源之后构建响应,发送响应,然后将所有的事件记录下来(日志)
    

5. nginx的安装与配置

5.1 安装

下载软件
[root@node7 ~]# wget https://nginx.org/download/nginx-1.20.2.tar.gz
[root@node7 ~]# ls
anaconda-ks.cfg  nginx-1.20.2.tar.gz
[root@node7 ~]# 


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

安装依赖环境
[root@node7 ~]# yum -y groups mark install 'Development Tools'
[root@node7 ~]# yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++ make 

创建日志存放目录
[root@node7 ~]# mkdir -p /var/log/nginx
[root@node7 ~]# chown -R nginx.nginx /var/log/nginx
[root@node7 ~]# ll -d /var/log/nginx
drwxr-xr-x. 2 nginx nginx 6 Sep  2 10:57 /var/log/nginx
[root@node7 ~]# 

编译安装
[root@node7 ~]# ls
anaconda-ks.cfg  nginx-1.20.2.tar.gz
[root@node7 ~]# tar xf nginx-1.20.2.tar.gz 
[root@node7 ~]# cd nginx-1.20.2
[root@node7 nginx-1.20.2]# ./configure \
> --prefix=/usr/local/nginx \  //指定安装位置
> --user=nginx \  //指定用户
> --group=nginx \  //指定组
> --with-debug \   //debug功能打开
> --with-http_ssl_module \  //将ssl功能打开
> --with-http_realip_module \  //转发realip功能打开
> --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@node7 nginx-1.20.2]# make
[root@node7 nginx-1.20.2]# make install

5.2 nginx安装后配置

[root@node7 ~]# ls /usr/local/nginx/
conf  html  logs  sbin
[root@node7 ~]# 

配置环境变量
[root@node7 ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
[root@node7 ~]# source /etc/profile.d/nginx.sh
[root@node7 ~]# 


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


启动nginx
[root@node7 ~]# nginx
[root@node7 ~]# 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             [::]:*            
[root@node7 ~]# 

关闭nginx
[root@node7 ~]# nginx -s stop
[root@node7 ~]# ss -antl
State  Recv-Q Send-Q  Local Address:Port   Peer Address:Port Process 
LISTEN 0      128           0.0.0.0:22          0.0.0.0:*            
LISTEN 0      128              [::]:22             [::]:*            
[root@node7 ~]# 
  • 提供网站内容
[root@node7 html]# pwd
/usr/local/nginx/html
[root@node7 html]# ls
50x.html  index.html
[root@node7 html]# echo 'hello world' > index.html 
[root@node7 html]# 
  • 关闭防火墙
[root@node7 ~]# systemctl disable --now firewalld
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@node7 ~]# setenforce 0
[root@node7 ~]# vim /etc/selinux/config 
  • 访问

在这里插入图片描述

5.3 配置service file

[root@node7 ~]# cd /usr/lib/systemd/system
[root@node7 system]# cp sshd.service nginx.service 
[root@node7 system]# vim nginx.service 
[root@node7 system]# cat nginx.service 
[Unit]
Description=web server daemon
After=network.target

[Service]
Type=foring
ExecStart=/usr/local/nginx/sbin/nginx
ExecStop=/usr/local/nginx/sbin/nginx -s stop
ExecReload=/usr/local/nginx/sbin/nginx -s reload
KillMode=process
Restart=on-failure
RestartSec=42s

[Install]
WantedBy=multi-user.target
[root@node7 system]# systemctl daemon-reload
[root@node7 system]# 

开机自启
[root@node7 ~]# systemctl enable --now nginx
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service.
[root@node7 ~]# 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             [::]:*            
[root@node7 ~]# 

5.4 查看帮助

[root@node7 ~]# nginx -h
nginx version: nginx/1.20.2
Usage: nginx [-?hvVtTq] [-s signal] [-p prefix]
             [-e filename] [-c filename] [-g directives]

Options:
  -?,-h         : this help
  -v            : show version and exit
  -V            : show version and configure options then exit
  -t            : test configuration and exit
  -T            : test configuration, dump it and exit
  -q            : suppress non-error messages during configuration testing
  -s signal     : send signal to a master process: stop, quit, reopen, reload
  -p prefix     : set prefix path (default: /usr/local/nginx/)
  -e filename   : set error log file (default: /var/log/nginx/error.log)
  -c filename   : set configuration file (default: conf/nginx.conf)
  -g directives : set global directives out of configuration file

[root@node7 ~]# 
        
选项:
-h:这个帮助
-v:显示版本并退出
-V:显示版本并配置选项,然后退出
-t:测试配置并退出
-T:测试配置,下载并退出
-q:在配置测试时抑制非错误消息
向主进程发送信号:停止,退出,重新打开,重新加载
设置前缀路径(默认为/usr/local/nginx/)
-e filename:设置错误日志文件(默认为/var/log/nginx/error.log)
-c filename:设置配置文件(默认为conf/nginx.conf),将配置文件copy一份,修改新的配置文件,使用-c指定配置文件
-g directives:将全局指令从配置文件中设置出来

5.5 nginx参数

[root@node7 ~]# nginx -v
nginx version: nginx/1.20.2
[root@node7 ~]# nginx -V
nginx version: nginx/1.20.2
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-4) (GCC) 
built with OpenSSL 1.1.1k  FIPS 25 Mar 2021
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
[root@node7 ~]# 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@node7 ~]# 

5.6 查看日志

[root@node7 nginx]# tail -4 /var/log/nginx/access.log 
192.168.232.1 - - [02/Sep/2022:11:10:46 +0800] "GET / HTTP/1.1" 200 12 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36"
192.168.232.1 - - [02/Sep/2022:11:10:46 +0800] "GET /favicon.ico HTTP/1.1" 404 555 "http://192.168.232.128/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36"
192.168.232.1 - - [03/Sep/2022:17:36:20 +0800] "GET / HTTP/1.1" 200 12 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36"
192.168.232.1 - - [03/Sep/2022:17:36:20 +0800] "GET /favicon.ico HTTP/1.1" 404 555 "http://192.168.232.128/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36"
[root@node7 nginx]# 


tail -1f  /var/log/nginx/access.log //f一直看

[root@node7 nginx]# tail -1f /var/log/nginx/access.log 
192.168.232.1 - - [03/Sep/2022:17:36:20 +0800] "GET /favicon.ico HTTP/1.1" 404 555 "http://192.168.232.128/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36"
192.168.232.1 - - [03/Sep/2022:17:43:00 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36"
192.168.232.1 - - [03/Sep/2022:17:43:01 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36"
192.168.232.1 - - [03/Sep/2022:17:43:19 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36"

5.7 查看nginx配置文件

[root@node7 nginx]# pwd
/usr/local/nginx
[root@node7 nginx]# ls
client_body_temp  fastcgi_temp  logs        sbin       uwsgi_temp
conf              html          proxy_temp  scgi_temp
[root@node7 nginx]# ls logs/
nginx.pid

[root@node7 nginx]# ls sbin/nginx 
sbin/nginx //主程序
[root@node7 nginx]# file sbin/nginx
sbin/nginx: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=6cba6ae50ddfdca253fab5a2bb6f5789de25aac5, with debug_info, not stripped
[root@node7 nginx]# 

[root@node7 nginx]# ls html/  //网站
50x.html  index.html
[root@node7 nginx]# 


主配置文件
[root@node7 nginx]# cd conf/
[root@node7 conf]# ls
fastcgi.conf            koi-win             scgi_params
fastcgi.conf.default    mime.types          scgi_params.default
fastcgi_params          mime.types.default  uwsgi_params
fastcgi_params.default  nginx.conf          uwsgi_params.default
koi-utf                 nginx.conf.default  win-utf
[root@node7 conf]# ls nginx.conf
nginx.conf
[root@node7 conf]# 

6. nginx的配置文件详解

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

    • 默认启动nginx时,使用的配置文件是:安装路径/conf/nginx.conf文件
    • 可以在启动nginx时通过-c选项来指定要读取的配置文件
    • 将想修改的配置文件复制一下,进行修改,使用-c指定
  • nginx常见的配置文件及其作用

配置文件作用
nginx.confnginx的基本配置文件
mime.typesMIME类型关联的扩展文件
fastcgi.conf与fastcgi相关的配置
proxy.conf与proxy相关的配置,编译proxy或者yum装的时候有
sites.conf配置nginx提供的网站,包括虚拟主机,编译proxy或者yum装的时候有
[root@node7 conf]# pwd
/usr/local/nginx/conf
[root@node7 conf]# ls
fastcgi.conf            koi-win             scgi_params
fastcgi.conf.default    mime.types          scgi_params.default
fastcgi_params          mime.types.default  uwsgi_params
fastcgi_params.default  nginx.conf          uwsgi_params.default
koi-utf                 nginx.conf.default  win-utf
[root@node7 conf]# 

6.1 nginx.conf配置详解

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

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

    derective value1 [value2 ...];
      键 值12....) ;
      
    user  nginx;
    worker_processes  1;
      
    events {
        worker_connections  1024;
    }
    
    处理多个进程用worker_processes  1;X worker_connections  1024; = 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;
      
        
      $remote_addr  远程地址
      $remote_user  远程用户
      $time_local   本地时间
      $request 请求资源
      $status 状态
      $body_bytes_sent  发送的字节数
      $http_referer 从哪里跳转过来的
      $http_user_agent 是什么浏览器
      $http_x_forwarded_for 从哪里转发过来的
      
    • 自定义变量:set var_name value

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

daemon {on|off};    //是否以守护进程方式运行nginx,调试时应设置为off,当你的nginx访问不了需要调试


Syntax:	daemon on | off; //语法
Default:	daemon on;  //默认值
Context:	main  //上下文


配置文件改成下面一直在前台访问:
user  nginx;
worker_processes  1;
daemon  off;



master_process {on|off};    //是否以master/worker模型来运行nginx,调试时可以设置为off
master用来接任务,worker用来处理

Syntax:	master_process on | off;
Default:	
master_process on;
Context:	main

当前进程:
[root@node7 ~]# ps -ef|grep nginx
root        2769       1  0 16:38 ?        00:00:00 nginx: master process nginx
nginx       2770    2769  0 16:38 ?        00:00:00 nginx: worker process
root      232686    1659  0 18:09 pts/0    00:00:00 vim nginx.conf
root      272427  261212  0 18:26 pts/2    00:00:00 grep --color=auto nginx
[root@node7 ~]# 

配置文件:
user  nginx;
worker_processes  1;
daemon on;
master_process off;

重新启动:
[root@node7 conf]# nginx -s stop 
[root@node7 conf]# nginx

现在进程:
[root@node7 ~]# ps -ef|grep nginx
root      321699       1  0 18:37 ?        00:00:00 nginx
root      322085  261212  0 18:38 pts/2    00:00:00 grep --color=auto nginx
[root@node7 ~]# 


error_log 位置 级别;    //配置错误日志

配置文件:
user  nginx;
worker_processes  1;
daemon on;
master_process off;

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

[root@node7 conf]# nginx -s stop 
[root@node7 conf]# nginx
[root@node7 conf]# 


[root@node7 ~]# ls /usr/local/nginx/logs/
error.log  nginx.pid
[root@node7 ~]# 

[root@node7 ~]# curl 192.168.232.128
hello world
[root@node7 ~]# curl 192.168.232.128/12121
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.2</center>
</body>
</html>
[root@node7 ~]# tail /usr/local/nginx/logs/error.log 
2022/09/03 18:43:30 [error] 331414#0: *1 open() "/usr/local/nginx/html/112" failed (2: No such file or directory), client: 192.168.232.1, server: localhost, request: "GET /112 HTTP/1.1", host: "192.168.232.128"
2022/09/03 18:43:55 [error] 331414#0: *4 open() "/usr/local/nginx/html/12121" failed (2: No such file or directory), client: 192.168.232.128, server: localhost, request: "GET /12121 HTTP/1.1", host: "192.168.232.128"
[root@node7 ~]# 
  • error_log里的位置和级别能有以下可选项:
位置级别
file (文件)stderr (标准错误) syslog:server=address[,parameter=value] memory:sizedebug:若要使用debug级别,需要在编译nginx时使用–with-debug选项 info notice warn error crit alert emerg
  • 级别越低,记录越详细,debug是最低级别
  • 级别越高,记录越关键,emerg是最高级别

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

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

配置文件:
user  nginx;
worker_processes  1;
daemon on;
master_process off;


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

配置文件中:
pid        logs/nginx.pid;

[root@node7 ~]# ls /usr/local/nginx/logs/
error.log  nginx.pid
[root@node7 ~]# 


worker_rlimit_nofile number;    //设置所有worker进程最大可以打开的文件数,默认为1024
[root@node7 ~]# ulimit -n
1024
[root@node7 ~]# 


Syntax:	worker_rlimit_nofile number;
Default:	—
Context:	main

配置文件:
user  nginx;
worker_processes  1;
daemon on;
master_process off;
worker_rlimit_nofile 65535; 


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

6.4 优化性能的配置参数

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

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核心

Syntax:	worker_cpu_affinity cpumask ...;
worker_cpu_affinity auto [cpumask];
Default:	—
Context:	main

配置文件:
user  nginx;
worker_processes  4;
daemon on;
master_process off;
worker_rlimit_nofile 65535;
worker_cpu_affinity 0001 0010 0100 1000;

[root@node7 ~]# ps -elf|grep nginx
1 S root      354957       1  0  80   0 - 20521 -      18:46 ?        00:00:00 nginx
0 S root      652945  261212  0  80   0 -  2302 -      19:58 pts/2    00:00:00 grep --color=auto nginx
[root@node7 ~]# 



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

配置文件:
user  nginx;
worker_processes  4;
worker_priority -20;
worker_rlimit_nofile 65535;
worker_cpu_affinity 0001 0010 0100 1000;

[root@node7 conf]# nginx -s reload


[root@node7 ~]# ps -elf|grep nginx
1 S root      691526       1  0  80   0 - 20408 -      20:07 ?        00:00:00 nginx: master process nginx
5 S nginx     691527  691526  0  60 -20 - 28558 do_epo 20:07 ?        00:00:00 nginx: worker process
5 S nginx     691528  691526  0  60 -20 - 28558 do_epo 20:07 ?        00:00:00 nginx: worker process
5 S nginx     691529  691526  0  60 -20 - 28558 do_epo 20:07 ?        00:00:00 nginx: worker process
5 S nginx     691530  691526  0  60 -20 - 28558 do_epo 20:07 ?        00:00:00 nginx: worker process
0 S root      692217  261212  0  80   0 -  2302 -      20:07 pts/2    00:00:00 grep --color=auto nginx
[root@node7 ~]# 

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

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

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

Syntax:	accept_mutex on | off;
Default:	
accept_mutex off;
Context:	events

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



use [epoll | rtsig | select | poll];    //指明使用的事件模型,建议让nginx自行选择
  
  
worker_connections #;    //每个进程能够接受的最大连接数
  
Syntax:	worker_connections number;
Default:	
worker_connections 512;
Context:	events

  
4x1024  
配置文件:
events {
    worker_connections  8000;
} 

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

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

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

Syntax:	keepalive_requests number;
Default:	
keepalive_requests 1000;
Context:	http, server, location
This directive appeared in version 0.8.0.

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

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

msie6:微软IE浏览器6

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

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


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


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


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

  • 网络界面 192.168.232.128
request headers: 请求头
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9
Cache-Control: max-age=0
Connection: keep-alive
Host: 192.168.232.128
If-Modified-Since: Fri, 02 Sep 2022 03:08:21 GMT
If-None-Match: "631173a5-c"
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36
  
接受编码:gzip压缩
接收语言:应用,zh型;
cache - control:
连接:
Upgrade-Insecure-Requests: 1
用户代理:
    
    
    
response headers: 接收到的数据包
Connection: keep-alive
Date: Sat, 03 Sep 2022 12:44:17 GMT
ETag: "631173a5-c"
Last-Modified: Fri, 02 Sep 2022 03:08:21 GMT
Server: nginx/1.20.2
    
连接:

日期:202293日星期六12:44:17 GMT

ETag:631173 a5-c”

最后修改日期:202292日星期五格林尼治时间03:08:21

服务器:nginx / 1.20.2    
    
general
equest URL: http://192.168.232.128/
Request Method: GET
Status Code: 304 OK
Remote Address: 192.168.232.128:80
Referrer Policy: strict-origin-when-cross-origin    

GET:从服务器获取资源      
      
装备的URL: http://192.168.232.128/。
请求方法:
状态码:304 OK
远程地址:192.168.232.128:80
介绍人政策:strict-origin-when-cross-origin      

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


[root@node7 ~]# ls /usr/local/nginx/html/
50x.html  index.html
[root@node7 ~]# 

[root@node7 ~]# cd /usr/local/nginx/conf/
[root@node7 conf]# vim fastcgi.conf
[root@node7 conf]# 


fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;

fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
如果访问不了
/scripts改为---$document_root

6.8 常需要进行调整的参数

  • worker_processes—CPU核心数
  • worker_connections
  • worker_cpu_affinity—绑定CPU
  • worker_priority—优先级

6.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>,一个server就是一个网站
    listen 80;
    server_name localhost;
    location / {//请求级别,类似于httpd中的<Location>,用于定义URL与本地文件系统的映射关系
      root html;
      index index.html index.htm;
    }
  }
}
  • http{}段配置指令:
  • server {}:定义一个虚拟主机
server {
  listen 80;
  server_name www.idfsoft.com;
  root "/vhosts/web";
}


配置文件:
#gzip  on;

    server {
        listen  8080;
        server_name www.example.com;
        location / {
            root /opt/mushuang;
            index index.html;
        }
    }

[root@node7 conf]# nginx -s reload
[root@node7 conf]# 
  
  
[root@node7 ~]# mkdir /opt/mushuang
[root@node7 ~]# cd /opt/mushuang
[root@node7 mushuang]# echo '123456' > index.html
[root@node7 mushuang]# cat index.html
123456
[root@node7 mushuang]# 
 [root@node7 mushuang]# ss -antl
State  Recv-Q Send-Q  Local Address:Port   Peer Address:Port Process 
LISTEN 0      128           0.0.0.0:8080        0.0.0.0:*            
LISTEN 0      128           0.0.0.0:80          0.0.0.0:*            
LISTEN 0      128           0.0.0.0:22          0.0.0.0:*            
LISTEN 0      128              [::]:22             [::]:*            
[root@node7 mushuang]# 
  • 在这里插入图片描述

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

listen address[:port];
listen port;

配置文件:
server {
        listen  192.168.232.250:8080;
        server_name www.example.com;
        location / {
            root /opt/mushuang;
            index index.html;
        }
    }


[root@node7 conf]# nginx -s stop
[root@node7 conf]# nginx


添加ip
[root@node7 ~]# ip addr add 192.168.232.250/24 dev ens160
[root@node7 ~]# 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: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:0c:29:03:67:8a brd ff:ff:ff:ff:ff:ff
    inet 192.168.232.128/24 brd 192.168.232.255 scope global noprefixroute ens160
       valid_lft forever preferred_lft forever
    inet 192.168.232.250/24 scope global secondary ens160
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fe03:678a/64 scope link 
       valid_lft forever preferred_lft forever
[root@node7 ~]# 


[root@node7 ~]# 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    192.168.232.250:8080       0.0.0.0:*            
LISTEN 0      128            0.0.0.0:22         0.0.0.0:*            
LISTEN 0      128               [::]:22            [::]:*            
[root@node7 ~]# 

  • 访问 192.168.232.250:8080

在这里插入图片描述

  • 使用192.168.232.128

在这里插入图片描述

  • server_name NAME [...]; 后面可跟多个主机,名称可使用正则表达式或通配符
[root@node7 conf]# vim nginx.conf
[root@node7 conf]# pwd
/usr/local/nginx/conf
[root@node7 conf]# 

server {
        listen 8080;
        server_name *.example.com;
        location / {
            root /opt/mushuang;
            index index.html;
        }
    }

[root@node7 conf]# nginx -s stop
[root@node7 conf]# nginx
  • test.example.com

在这里插入图片描述

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

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

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

[root@node7 ~]# cd /usr/local/nginx/html/
[root@node7 html]# ls
50x.html  index.html
[root@node7 html]# mkdir test
[root@node7 html]# echo '6666' > test/index.html
[root@node7 html]# cat test/index.html
6666
[root@node7 html]# 


在这里插入图片描述

  • 使用别名
server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location /test {
            alias /usr/local/nginx/html/test;
            index index.html;
        }
        location / {
            root html;
            index  index.html index.htm;
        }

[root@node7 conf]# vim nginx.conf
[root@node7 conf]# nginx -s reload
[root@node7 conf]# 
  • http://192.168.232.128/test/

在这里插入图片描述

  • http://192.168.232.128/

在这里插入图片描述

  • 访问区别:

在这里插入图片描述

相关文章:

  • Vue element-ui表格嵌进度条
  • 前后数据传输协议规范
  • Unions
  • 基于springboot的地质灾害应急管理系统
  • Structures
  • 向量数据库入坑指南:聊聊来自元宇宙大厂 Meta 的相似度检索技术 Faiss
  • 电子邮件营销新趋势-自动化
  • ICT产业关联效应的国际比较——基于投入产出的分析
  • 【algorithm】算法学习----堆
  • Q_ENUM Q_ENUMS Q_ENUM_NS Q_FLAG Q_FLAGS Q_FLAG_NS
  • 国外5G行业应用产业政策分析及对我国的启示
  • 【C语言】文件输入输出操作
  • 【教3妹学算法-每日一题】竞赛题:6171. 和相等的子数组
  • 遗传算法GA求解非连续函数问题
  • 【电商营销】为什么需要从获取客户转向留住客户
  • ES10 特性的完整指南
  • Hibernate【inverse和cascade属性】知识要点
  • Nginx 通过 Lua + Redis 实现动态封禁 IP
  • oschina
  • Spring核心 Bean的高级装配
  • supervisor 永不挂掉的进程 安装以及使用
  • Vue.js-Day01
  • Vue2 SSR 的优化之旅
  • vue--为什么data属性必须是一个函数
  • 基于OpenResty的Lua Web框架lor0.0.2预览版发布
  • 提升用户体验的利器——使用Vue-Occupy实现占位效果
  • 我感觉这是史上最牛的防sql注入方法类
  • raise 与 raise ... from 的区别
  • shell使用lftp连接ftp和sftp,并可以指定私钥
  • 移动端高清、多屏适配方案
  • (AngularJS)Angular 控制器之间通信初探
  • (Mirage系列之二)VMware Horizon Mirage的经典用户用例及真实案例分析
  • (黑客游戏)HackTheGame1.21 过关攻略
  • (免费领源码)Java#Springboot#mysql农产品销售管理系统47627-计算机毕业设计项目选题推荐
  • (强烈推荐)移动端音视频从零到上手(上)
  • (亲测)设​置​m​y​e​c​l​i​p​s​e​打​开​默​认​工​作​空​间...
  • (十五)devops持续集成开发——jenkins流水线构建策略配置及触发器的使用
  • .[backups@airmail.cc].faust勒索病毒的最新威胁:如何恢复您的数据?
  • .htaccess 强制https 单独排除某个目录
  • .md即markdown文件的基本常用编写语法
  • .NET CF命令行调试器MDbg入门(三) 进程控制
  • .net websocket 获取http登录的用户_如何解密浏览器的登录密码?获取浏览器内用户信息?...
  • .NET 跨平台图形库 SkiaSharp 基础应用
  • .Net 垃圾回收机制原理(二)
  • .Net程序帮助文档制作
  • /var/lib/dpkg/lock 锁定问题
  • @font-face 用字体画图标
  • [ CTF ]【天格】战队WriteUp- 2022年第三届“网鼎杯”网络安全大赛(青龙组)
  • [20171106]配置客户端连接注意.txt
  • [2669]2-2 Time类的定义
  • [C#]winform部署PaddleOCRV3推理模型
  • [CLR via C#]11. 事件
  • [EULAR文摘] 脊柱放射学持续进展是否显著影响关节功能
  • [GN] DP学习笔记板子
  • [LeetCode]Spiral Matrix