nginx

发布时间:2022-07-01 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了nginx脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

nginx

    • 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的工作原理
      • 4.3 web服务器请求资的过程
    • 5.nginx的安装与配置
      • 5.1 nginx的安装
      • 5.2 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简介

Nginx (engine x) 是一个高性能的web反向代理服务器,同时也提供了IMAP/pop3/SMTP服务。Nginx是由伊戈尔·赛索耶夫为俄罗斯访问量第二的Rambler.ru站点(俄文:Рамблер)开发的,第一个公开版本0.1.0发布于2004年10月4日。 其将源代码以类BSD许可证的形式发布,因它的稳定性、丰富的功能集、简单的配置文件和低系统资源的消耗而闻名。2011年6月1日,nginx 1.0.4发布。 Nginx是一款轻量级的Web 服务器/反向代理服务器及子邮件(IMAP/POP3)代理服务器,在BSD-like 协议下发行。其特点是占有内存少并发能力强,事实上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中所配置的每个指令将会启动不同的模块去完成相应的工作。

  • URI:Uniform Resource Indentifier,统一资源标识符。用于定义全局范围内(包括但不仅限于互联网)去标识唯一的、定位一种资源访问路径的方式,或者命名方式,被称作统一资源标识符。这里的统一指的是路径格式上的统一。

  • URL:Uniform Resource Location,统一资源定位符,是URI的一个子集,用于描述在互联网上互联网资源的统一表示格式(PRotocol://host:port/path/to/file)

  • pv:Page View,打开了多少页面

  • UV:User View,独立IP量(UV的数量多说明访问的人多)

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进程。其中master充当整个进程组与用户的交互接口,同时对进程进行监护,管理worker进程来实现重启服务、平滑升级、更换日志文件、配置文件实时生效等功能。worker用来处理基本的网络事件,worker之间是平等的,他们共同竞争来处理来自客户端的请求。

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

nginx

web sever:web服务器的集群 application server : 应用服务器的集群 mencached: 缓存服务器的集群 backend: 后端 advaced I/O: 同步 sendfile,AIO 异步

工作方式: 在工作方式上,Nginx分为单工作进程和多工作进程两种模式。在单工作进程模式下,除主进程外,还有一个工作进程,工作进程是单线程的;在多工作进程模式下,每个工作进程包含多个线程。Nginx默认为单工作进程模式。

Nginx在启动后,会有一个master进程和多个worker进程。

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

nginx

4.3 web服务器请求资源的过程

nginx

首先我们客户端发送一个请求到Web服务器,请求首先是到网卡。

网卡将请求交由内核空间的内核处理,其实就是拆包了,发现请求的是80端口。

内核便将请求发给了在用户空间的Web服务器,Web服务器解包发现客户端 请求的index.html页面、

Web服务器便进行系统调用将请求发给内核

内核发现在请求的是一页面,便调用磁盘的驱动程序,连接磁盘

内核通过驱动调用磁盘取得的页面文件

内核将取得的页面文件保存在自己的缓存区域中便通知Web进程或线程来取相应的页面文件

Web服务器通过系统调用将内核缓存中的页面文件复制到进程缓存区域中

Web服务器取得页面文件来响应用户,再次通过系统调用将页面文件发给内核 内核进程页面文件的封装并通过网卡发送出去,当报文到达网卡时通过网络响应给客户端

5.nginx的安装与配置

5.1 nginx的安装

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

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

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

//下载nginx
[root@localhost ~]# wget http://nginx.org/download/nginx-1.21.3.tar.gz
--2021-10-25 23:25:56--  http://nginx.org/download/nginx-1.21.3.tar.gz
正在解析主机 nginx.org (nginx.org)... 52.58.199.22, 3.125.197.172, 2a05:d014:edb:5704::6, ...
正在连接 nginx.org (nginx.org)|52.58.199.22|:80... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:1066609 (1.0M) [application/octet-stream]
正在保存至: “nginx-1.21.3.tar.gz”

nginx-1.21.3.tar.gz       100%[=====================================>]   1.02M  28.3KB/s  用时 32s     

2021-10-25 23:26:30 (32.7 KB/s) - 已保存 “nginx-1.21.3.tar.gz” [1066609/1066609])

//编译安装
[root@localhost ~]# ls 
anaconda-ks.CFg  nginx-1.21.3.tar.gz
[root@localhost ~]# tar xf nginx-1.21.3.tar.gz 
[root@localhost ~]# cd nginx-1.21.3/
[root@localhost nginx-1.21.3]# ./configure 
--prefix=/usr/local/nginx 
--user=nginx 
--group=nginx 
--with-debug 
--with-http_ssl_module 
--with-http_realip_module 
--with-http_image_filter_module 
--with-http_gunzip_module 
--with-http_gzip_static_module 
--with-http_stub_status_module 
--http-log-path=/var/log/nginx/access.log 
--error-log-path=/var/log/nginx/error.log

[root@localhost nginx-1.21.3]# make -j $(grep 'processor' /proc/cpuinfo | wc -l) && make install

5.2 nginx安装后配置

//配置环境变量
[root@localhost ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
[root@localhost ~]# . /etc/profile.d/nginx.sh
[root@localhost ~]# which nginx		//成功找到nginx
/usr/local/nginx/sbin/nginx

//服务控制方式,使用nginx命令
    -t  //检查配置文件语法
    -v  //输出nginx的版本
    -c  //指定配置文件的路径
    -s  //发送服务控制信号,可选值有{stop|quit|reopen|reload},一般只用到stop和reload
	-V  //显示nginx服务器的版本号和nginx服务器的编译情况
	-h  //打印二进制文件nginx的用法
	-t -q //一起使用,如果配置文件无错误,将无任何输出
	-p  //用来改变nginx的安装路径,常用在平滑升级Nginx服务器的场合
	-g //用来补充nginx配置文件,向nginx服务指定启动时应用于全局的配置

//启动nginx,无需-s指定
[root@localhost ~]# nginx 
[root@localhost ~]# ss -anltu
Netid      State       recv-Q      Send-Q           Local Address:Port           Peer Address:Port      
tcp        LISTEN      0           128                    0.0.0.0:80                  0.0.0.0:*         
tcp        LISTEN      0           128                    0.0.0.0:22                  0.0.0.0:*         
tcp        LISTEN      0           128                       [::]:22                     [::]:*         

//-v输出nginx的版本
[root@localhost ~]# nginx -v
nginx version: nginx/1.21.3

//-V输出nginx的版本和编译安装nginx的命令,可以查看安装了哪些模块
[root@localhost ~]# nginx -V
nginx version: nginx/1.21.3
built by gcc 8.4.1 20200928 (red hat 8.4.1-1) (GCC) 
built with OpenSSL 1.1.1g FIPS  21 Apr 2020
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

//-h列出帮助文档
[root@localhost ~]# nginx -h
nginx version: nginx/1.21.3
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

//-t检查安装目录下/conf/nginx.conf文件语法
[root@localhost ~]# 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 ~]# cp /usr/local/nginx/conf/nginx.conf /opt/
[root@localhost ~]# cp /usr/local/nginx/conf/mime.types /opt/
[root@localhost ~]# ls /opt/
mime.types  nginx.conf		//修改拷贝到其他位置的配置文件nginx.conf
[root@localhost ~]# nginx -s stop;nginx -c /opt/nginx.conf 	//停止,然后马上启动,-c指定修改的配置文件nginx.conf
[root@localhost ~]# ss -anltu
Netid      State       Recv-Q      Send-Q           Local Address:Port           Peer Address:Port      
tcp        LISTEN      0           128                    0.0.0.0:80                  0.0.0.0:*         
tcp        LISTEN      0           128                    0.0.0.0:22                  0.0.0.0:*         
tcp        LISTEN      0           128                       [::]:22                     [::]:*         
//如果配置文件修改有误,取消-c,使用默认的配置文件
[root@localhost ~]# nginx -s stop;nginx 

6 nginx的配置文件详解

主配置文件:安装目录/conf/nginx.conf

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

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

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

6.1 nginx.conf配置详解

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

  • main配置段:全局配置段。其中main配置段中可能包含event配置段
  • event {}:定义event模型工作特性
  • http {}:定义http协议相关的配置

配置指令:要以分号结尾,语法格式如下:

derective value1 [value2 ...];

支持使用变量:

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

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

daemon {on|off};    //是否以守护进程方式运行nginx,调试时应设置为off
master_process {on|off};    //是否以master/worker模型来运行nginx,调试时可以设置为off
error_log 位置 级别;    //配置错误日志

error_log里的位置和级别能有以下可选项:

位置级别(递增)
filestderrSyslog:server=address[,parameter=value]memory:sizedebug:若要使用debug级别,需要在编译nginx时使用–with-debug选项infonoticewarnerrorcritalertemerg

级别越低记录的越详细 位置一般用的是file文件 级别一般默认的是error

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

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

参数user和group(可选)

//nginx安装过后配置文件中的user默认是nobody,但是配置文件中user参数是注释掉的,即使我们把注释去掉,默认user也不是nobody,是nginx
[root@localhost ~]# head -3 /usr/local/nginx/conf/nginx.conf

user  nginx nginx;
worker_processes  1;
[root@localhost ~]# ps -ef |grep nginx
root       43320       1  0 08:23 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      43321   43320  0 08:23 ?        00:00:00 nginx: worker process
root       43407    1434  0 08:23 pts/0    00:00:00 grep --color=auto nginx

参数worker_rlimit_nofile number Linux是有文件句柄限制的(open files),一般默认是1024,当超过这个数量便会报 Too many open files错误,修改nginx参数worker_rlimit_nofile number时,同时也需要修改系统的open file,使用命令ulimit -a可以查看句柄数

[root@localhost ~]# ulimit -a
core file size          (blocks, -c) unlimited
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 3026
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024	//句柄数
pipe size            (512 bytes, -p) 8
posix message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 3026
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

//修改nginx配置文件worker_rlimit_nofile number为65535
[root@localhost ~]# head -5 /usr/local/nginx/conf/nginx.conf

user  nginx nginx;
worker_processes  1;

worker_rlimit_nofile 65535;
[root@localhost ~]# nginx -s stop;nginx 

//修改系统允许打开的文件数,修改系统配置文件
[root@localhost ~]# tail -3 /etc/security/limits.conf 
# End of file	//最后添加下面两行
* soft nofile 65535             
* hard nofile 65535
#重启或重新打开终端

6.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值
  • 参数worker_processes nworker_cpu_affinity cpumask
//查看CPU核数
top - 08:47:49 up 36 min,  2 users,  load average: 0.06, 0.07, 0.07
Tasks: 203 total,   1 running, 202 sleeping,   0 stopped,   0 zombie
%Cpu0  :  0.7 us,  1.3 sy,  0.0 ni, 97.7 id,  0.0 wa,  0.0 hi,  0.3 si,  0.0 st
%Cpu1  :  0.3 us,  2.0 sy,  0.0 ni, 97.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
MiB Mem :    791.5 total,    115.1 free,    271.1 used,    405.3 buff/cache
MiB Swap:   2048.0 total,   2040.7 free,      7.2 used.    383.2 avail Mem 

//配置参数
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
[root@localhost ~]# head -4 /usr/local/nginx/conf/nginx.conf

user  nginx nginx;
worker_processes  2;
worker_cpu_affinity  0001 0010;
[root@localhost ~]# nginx -s stop;nginx 

使用top命令查看nginx运行 输入top命令之后按L搜索nginx,然后再按f

nginx

按f之后,空格开启下面这个功能,然后q退出

nginx

此时可以查看到nginx进程对应一个核心

nginx

  • 参数worker_priority 安装后默认优先级是0,可以再配置文件中修改优先级(优先级越高获得更多的CPU运行时间,更优先获得CPU运行的机会
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
[root@localhost ~]# head -6 /usr/local/nginx/conf/nginx.conf

user  nginx nginx;
worker_processes  2;
worker_cpu_affinity  0001 0010;
worker_rlimit_nofile 65535;
worker_priority -20;		//修改优先级为-20
[root@localhost ~]# nginx -s stop;nginx 
#优先级有-20到19,分别对应100到139

nginx

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

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

一个进程最大并发量最大为50000,但是实际配置时一般设为30000 并发量=(worker_processes*worker_connections)/2

配置并发量为30000

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
[root@localhost ~]# head -16 /usr/local/nginx/conf/nginx.conf

user  nginx nginx;
worker_processes  2;
worker_cpu_affinity  0001 0010;
worker_rlimit_nofile 65535;
worker_priority -20;
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  30000;
}
[root@localhost ~]# nginx -s stop;nginx 

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

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

6.8 常需要进行调整的参数

  • worker_processes
  • worker_connections
  • worker_cpu_affinity
  • 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>
    listen 80;
    server_name localhost;
    location / {//请求级别,类似于httpd中的<Location>,用于定义URL与本地文件系统的映射关系
      root html;
      index index.html index.htm;
    }
  }
}

http{}段配置指令:

  • server {}:定义一个虚拟主机,示例如下:
    server {
        listen 81;
        server_name test.example.COM;

        location / {
            root   html/test;
            index index.html;
        }
    }
[root@localhost ~]# cd /usr/local/nginx/html/
[root@localhost html]# mkdir test
[root@localhost html]# echo 'test' > test/index.html
[root@localhost html]# nginx -s stop;nginx 
[root@localhost html]# ss -anltu
Netid      State       Recv-Q      Send-Q           Local Address:Port           Peer Address:Port      
tcp        LISTEN      0           128                    0.0.0.0:80                  0.0.0.0:*         
tcp        LISTEN      0           128                    0.0.0.0:81                  0.0.0.0:*         
tcp        LISTEN      0           128                    0.0.0.0:22                  0.0.0.0:*         
tcp        LISTEN      0           128                       [::]:22                     [::]:*         

nginx

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配置段,定义路径别名

[root@localhost ~]# mkdir -p /var/www/html
[root@localhost ~]# cd /var/www/html
[root@localhost html]# mv /usr/local/nginx/html/test/ .
[root@localhost html]# ls
test
[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf
   server {
        listen 81;
        server_name test.example.com;

        location / {
            alias  /var/www/html/;	//写绝对路径
            index index.html index.htm;
        }
    }
[root@localhost ~]# nginx -s stop;nginx

index file; 默认主页面

index index.php index.html;
  • 错误页面配置

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

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

定义之前访问不存在的资源

nginx

[root@localhost ~]# cd /usr/local/nginx/conf/
[root@localhost conf]# vim nginx.conf
#取消下面一行的注释,当访问的资源不存在,状态码为404时,用安装目录下html/404.html文件来响应
49         error_page  404              /404.html;

[root@localhost ~]# cd /usr/local/nginx/html/		//在html目录下定义404.html文件
[root@localhost html]# ls
 404.html   50x.html  '第十二章 http协议_忘情OK_51CTO博客_files'   index.html
 
 //重启nginx
[root@localhost html]# nginx -s stop;nginx
[root@localhost html]# ss -anltu
Netid      State       Recv-Q      Send-Q           Local Address:Port           Peer Address:Port      
tcp        LISTEN      0           128                    0.0.0.0:80                  0.0.0.0:*         
tcp        LISTEN      0           128                    0.0.0.0:22                  0.0.0.0:*         
tcp        LISTEN      0           128                       [::]:22                     [::]:*         

定义完错误页面,此时就会访问到定义的404.html,但是状态码还是404

nginx

指定状态码

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
49         error_page  404   =200           /404.html;	//加上 =(状态码)
[root@localhost ~]# nginx -s stop;nginx

此时访问,状态码就变成你设置的状态码

nginx

脚本宝典总结

以上是脚本宝典为你收集整理的nginx全部内容,希望文章能够帮你解决nginx所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。