web服务之nginx核心配置

Nginx 核心配置详解

配置文件说明

nginx 官方帮助文档

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

tengine 帮助文档

http://tengine.taobao.org/nginx_docs/cn/docs/

Nginx的配置文件的组成部分:
主配置文件:nginx.conf
子配置文件: include conf.d/*.conf
fastcgi, uwsgi,scgi 等协议相关的配置文件
mime.types:支持的mime类型,MIME(Multipurpose Internet Mail Extensions)多用途互联网邮
件扩展类型,MIME消息能包含文本、图像、音频、视频以及其他应用程序专用的数据,是设定某
种扩展名的文件用一种应用程序来打开的方式类型,当该扩展名文件被访问的时候,浏览器会自动
使用指定应用程序来打开。多用于指定一些客户端自定义的文件名,以及一些媒体文件打开方式。

MIME参考文档:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_Types

nginx 配置文件格式说明

配置文件由指令与指令块构成
每条指令以;分号结尾,指令与值之间以空格符号分隔
可以将多条指令放在同一行,用分号分隔即可,但可读性差,不推荐
指令块以{ }大括号将多条指令组织在一起,且可以嵌套指令块
include语句允许组合多个配置文件以提升可维护性
使用#符号添加注释,提高可读性
使用$符号使用变量
部分指令的参数支持正则表达式

Nginx 主配置文件的配置指令方式:

directive value [value2 ...];
注意
(1) 指令必须以分号结尾
(2) 支持使用配置变量
内建变量:由Nginx模块引入,可直接引用
自定义变量:由用户使用set命令定义,格式: set variable_name value;
引用变量:$variable_name

主配置文件结构:四部分

main block:主配置段,即全局配置段,对http,mail都有效
#事件驱动相关的配置
event {
...
}
#http/https 协议相关配置段
http {
...
}
#默认配置文件不包括下面两个块
#mail 协议相关配置段
mail {
...
}
#stream 服务器相关配置段
stream {
...
}

默认的nginx.conf 配置文件格式说明

#全局配置端,对全局生效,主要设置nginx的启动用户/组,启动的工作进程数量,工作模式,Nginx的PID
路径,日志路径等。
user nginx nginx;
worker_processes 1; #启动工作进程数数量
events { #events设置快,主要影响nginx服务器与用户的网络连接,比如是否允许同时接受多个网络连
接,使用哪种事件驱动模型处理请求,每个工作进程可以同时支持的最大连接数,是否开启对多工作进程下的
网络连接进行序列化等。
worker_connections 1024; #设置单个nginx工作进程可以接受的最大并发,作为web服务器
的时候最大并发数为worker_connections * worker_processes,作为反向代理的时候为
(worker_connections * worker_processes)/2
}
http { #http块是Nginx服务器配置中的重要部分,缓存、代理和日志格式定义等绝大多数功能和第三方模
块都可以在这设置,http块可以包含多个server块,而一个server块中又可以包含多个location块,
server块可以配置文件引入、MIME-Type定义、日志自定义、是否启用sendfile、连接超时时间和单个链
接的请求上限等。
include mime.types;
default_type application/octet-stream;
sendfile on; #作为web服务器的时候打开sendfile加快静态文件传输,指定是否使用
sendfile系统调用来传输文件,sendfile系统调用在两个文件描述符之间直接传递数据(完全在内核中操
作),从而避免了数据在内核缓冲区和用户缓冲区之间的拷贝,操作效率很高,被称之为零拷贝,硬盘 >>
kernel buffer (快速拷贝到kernelsocket buffer) >>协议栈。
keepalive_timeout 65; #长连接超时时间,单位是秒
server { #设置一个虚拟机主机,可以包含自己的全局快,同时也可以包含多个location模块。比如
本虚拟机监听的端口、本虚拟机的名称和IP配置,多个server 可以使用一个端口,比如都使用80端口提供
web服务、
     listen 80; #配置server监听的端口
     server_name localhost; #本server的名称,当访问此名称的时候nginx会调用当前
serevr内部的配置进程匹配。
    location / { #location其实是server的一个指令,为nginx服务器提供比较多而且灵活的指
令,都是在location中体现的,主要是基于nginx接受到的请求字符串,对用户请求的UIL进行匹配,并对特
定的指令进行处理,包括地址重定向、数据缓存和应答控制等功能都是在这部分实现,另外很多第三方模块的
配置也是在location模块中配置。
   root html; #相当于默认页面的目录名称,默认是安装目录的相对路径,可以使用绝对路
径配置。
   index index.html index.htm; #默认的页面文件名称
   }
   error_page 500 502 503 504 /50x.html; #错误页面的文件名称
   location = /50x.html { #location处理对应的不同错误码的页面定义到/50x.html,这个
跟对应其server中定义的目录下。
   root html; #定义默认页面所在的目录
  }
}
#和邮件相关的配置
#mail {
# ...
# } mail 协议相关配置段
#tcp代理配置,1.9版本以上支持
#stream {
# ...
# } stream 服务器相关配置段
#导入其他路径的配置文件
#include /apps/nginx/conf.d/*.conf
}

全局配置

Main 全局配置段常见的配置指令分类
正常运行必备的配置
优化性能相关的配置
用于调试及定位问题相关的配置
事件驱动相关的配置

全局配置说明:

user nginx nginx; #启动Nginx工作进程的用户和组
worker_processes [number | auto]; #启动Nginx工作进程的数量,一般设为和CPU核心数相同
worker_cpu_affinity 00000001 00000010 00000100 00001000; #将Nginx工作进程绑定到指定
的CPU核心,默认Nginx是不进行进程绑定的,绑定并不是意味着当前nginx进程独占以一核心CPU,但是可以
保证此进程不会运行在其他核心上,这就极大减少了nginx的工作进程在不同的cpu核心上的来回跳转,减少
了CPU对进程的资源分配与回收以及内存管理等,因此可以有效的提升nginx服务器的性能。
CPU MASK: 00000001:0号CPU
00000010:1号CPU
10000000:7号CPU
#示例:
worker_cpu_affinity 0001 0010 0100 1000;第0号---第3号CPU
worker_cpu_affinity 0101 1010;
#示例
worker_processes 4;
worker_cpu_affinity 00000010 00001000 00100000 10000000;
[root@centos8 ~]# ps axo pid,cmd,psr | grep nginx
31093 nginx: master process /apps 1
34474 nginx: worker process 1
34475 nginx: worker process 3
34476 nginx: worker process 5
34477 nginx: worker process 7
35751 grep nginx
#错误日志记录配置,语法:error_log file [debug | info | notice | warn | error | crit
| alert | emerg]
#error_log logs/error.log;
#error_log logs/error.log notice;
error_log /apps/nginx/logs/error.log error;
#pid文件保存路径
pid /apps/nginx/logs/nginx.pid;
worker_priority 0;  #工作进程优先级,-20~20(19)
worker_rlimit_nofile 65536;   #所有worker进程能打开的文件数量上限,包括:Nginx的所有连接(例
如与代理服务器的连接等),而不仅仅是与客户端的连接,另一个考虑因素是实际的并发连接数不能超过系统级别的最大打开文件数的限制.最好与ulimit -n 或者limits.conf的值保持一致,
#修改pam限制
[root@centos8 ~]# cat /etc/security/limits.conf
* soft nofile 1000000
* hard nofile 1000000
[root@centos8 ~]# watch -n1 'ps -axo pid,cmd,nice | grep nginx #验证进程优先级
daemon off; #前台运行Nginx服务用于测试、docker等环境。
master_process off|on; #是否开启Nginx的master-worker工作模式,仅用于开发调试场景,默认为on
events {
worker_connections 65536; #设置单个工作进程的最大并发连接数
use epoll; #使用epoll事件驱动,Nginx支持众多的事件驱动,比如:select、poll、epoll,只
能设置在events模块中设置。
accept_mutex on; #on为同一时刻一个请求轮流由work进程处理,而防止被同时唤醒所有worker,避
免多个睡眠进程被唤醒的设置,默认为off,新请求会唤醒所有worker进程,此过程也称为"惊群",因此
nginx刚安装完以后要进行适当的优化。建议设置为on
multi_accept on; #on时Nginx服务器的每个工作进程可以同时接受多个新的网络连接,此指令默认
为off,即默认为一个工作进程只能一次接受一个新的网络连接,打开后几个同时接受多个。建议设置为on
}

范例: 实现 nginx 的高并发配置

[root@centos7 ~]# ulimit -n 102400
[root@centos7 ~]# while true;do ab -c 5000 -n 10000 http://172.31.0.8/;sleep 0.5;done

#默认配置不支持高并发,会出现以下错误日志
[root@centos8 conf]#tail /apps/nginx/logs/error.log
2020/09/24 21:19:33 [crit] 41006#0: *1105860 open() "/apps/nginx/html/50x.html"
failed (24: Too many open files), client: 172.31.0.7, server: localhost, request:
"GET / HTTP/1.0", host: "172.31.0.8"
2020/09/24 21:19:33 [crit] 41006#0: accept4() failed (24: Too many open files)
2020/09/24 21:19:33 [crit] 41006#0: *1114177 open()
"/apps/nginx/html/index.html" failed (24: Too many open files), client: 172.31.0.7,
server: localhost, request: "GET / HTTP/1.0", host: "172.31.0.8"
#修改配置
[root@centos8 ~]# vim /etc/security/limits.conf
* - nproc 100000

[root@centos8 ~]# vim /apps/nginx/conf/nginx.conf
worker_rlimit_nofile 100000;
[root@centos8 ~]# systemctl restart nginx

http 配置块

http 协议相关的配置结构

http {
  ...
  ... #各server的公共配置
  server { #每个server用于定义一个虚拟主机,第一个server为默认虚拟服务器
  ...
  }
  server {
  ...
    server_name #虚拟主机名
    root #主目录
    alias #路径别名
    location [OPERATOR] URL { #指定URL的特性
    ...
      if CONDITION {
    ...
      }
    }
  }
}

http 协议配置说明

http {
include mime.types; #导入支持的文件类型,是相对于/apps/nginx/conf的目录
default_type application/octet-stream; #除mime.types中文件类型外,设置其它文件默认
类型,访问其它类型时会提示下载不匹配的类型文件
#日志配置部分
#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; #在开启了sendfile的情况下,合并请求后统一发送给客户端,必须开启
sendfile
#tcp_nodelay off; #在开启了keepalived模式下的连接是否启用TCP_NODELAY选项,当为
off时,延迟0.2s发送,默认On时,不延迟发送,立即发送用户响应报文。
#keepalive_timeout 0;
keepalive_timeout 65 65; #设置会话保持时间,第二个值为响应首部:keep-
Alived:timeout=65,可以和第一个值不同
#gzip on; #开启文件压缩
server {
listen 80; #设置监听地址和端口
server_name localhost; #设置server name,可以以空格隔开写多个并支持正则表达式,
如:*.magedu.com www.longxuan.* ~^wwwd+.longxuan.com$ default_server
#charset koi8-r; #设置编码格式,默认是俄语格式,建议改为utf-8
#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$ { #以http的方式转发php请求到指定web服务器
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ .php$ { #以fastcgi的方式转发php请求到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 { #拒绝web形式访问指定文件,如很多的网站都是通过.htaccess文件来
改变自己的重定向等功能。
# deny all;
#}
location ~ /passwd.html {
deny all;
}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server { #自定义虚拟server
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm; #指定默认网页文件,此指令由
ngx_http_index_module模块提供
# }
#}
# HTTPS server
#
#server { #https服务器配置
# 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;
# }
#}

MIME

#在响应报文中将指定的文件扩展名映射至MIME对应的类型
include /etc/nginx/mime.types;
default_type application/octet-stream;#除mime.types中的类型外,指定其它文件的默认
MIME类型,浏览器一般会提示下载
types {
text/html html;
image/gif gif;
image/jpeg jpg;
}

#MIME参考文档:
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_Types

指定响应报文server首部

#是否在响应报文中的Content-Type显示指定的字符集,默认off不显示
charset charset | off;
#示例
charset utf-8;
#是否在响应报文的Server首部显示nginx版本
server_tokens on | off | build | string;

范例: 修改server字段

如果想自定义响应报文的nginx版本信息,需要修改源码文件,重新编译
如果server_tokens on,修改 src/core/nginx.h 修改第13-14行,如下示例
#define NGINX_VERSION "1.68.9"
#define NGINX_VER "long/" NGINX_VERSION
如果server_tokens off,修改 src/http/ngx_http_header_filter_module.c
第49行,如下示例:
static char ngx_http_server_string[] = "Server: nginx" CRLF;
把其中的nginx改为自己想要的文字即可,如:long

范例: 修改 Server 头部信息

[root@centos8 ~]# vim /usr/local/src/nginx-1.18.0/src/core/nginx.h
#define NGINX_VERSION "1.68.9"
#define NGINX_VER "long/" NGINX_VERSION
[root@centos8 ~]# vim nginx-1.18.0/src/http/ngx_http_header_filter_module.c
static u_char ngx_http_server_string[] = "Server: long-nginx" CRLF;

核心配置示例

基于不同的IP、不同的端口以及不用得域名实现不同的虚拟主机,依赖于核心模块ngx_http_core_module实现。

#定义子配置文件路径
[root@centos8 ~]# mkdir /apps/nginx/conf/conf.d -p
[root@centos8 ~]# vim /apps/nginx/conf/nginx.conf
http {
    ......
    include /apps/nginx/conf/conf.d/*.conf; #在配置文件的最后面添加此行,注意不要放在最前
面,会导致前面的命令无法生效
}

#创建PC网站配置
[root@sz-kx-centos8 ~]# vim /apps/nginx/conf/conf.d/pc.conf
server {
    listen 80;
    server_name www.longxuan.vip;
    location / {
        root /data/nginx/html/pc;                            
    }
}

#创建存放主页面目录
[root@sz-kx-centos8 ~]# mkdir /data/nginx/html/pc -p
[root@sz-kx-centos8 ~]# echo "long pc web" > /data/nginx/html/pc/index.html

#检查语法
[root@sz-kx-centos8 ~]# nginx -t
nginx: the configuration file /apps/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /apps/nginx/conf/nginx.conf test is successful

#重新加载nginx
[root@sz-kx-centos8 ~]# nginx -s reload

#测试访问
[root@localhost ~]# curl www.longxuan.vip
long pc web

#指定第二个站点名称
[root@sz-kx-centos8 ~]# vim /apps/nginx/conf/conf.d/moba.conf
server {
    listen 80;
    server_name mq.longxuan.vip;
    location / {
        root /data/nginx/html/moba;                          
    }
}

#创建存放主页面目录
[root@sz-kx-centos8 ~]# mkdir /data/nginx/html/moba -p
[root@sz-kx-centos8 ~]# echo "longwang moba web" > /data/nginx/html/moba/index.html

#检查语法
[root@sz-kx-centos8 ~]# nginx -t
nginx: the configuration file /apps/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /apps/nginx/conf/nginx.conf test is successful

#重新加载nginx
[root@sz-kx-centos8 ~]# nginx -s reload
#测试访问
[root@localhost ~]# curl mq.longxuan.vip
longwang moba web

root 与 alias

root:指定web的家目录,在定义location的时候,文件的绝对路径等于 root+location
范例:

[root@sz-kx-centos8 ~]# vim /apps/nginx/conf/conf.d/pc.conf
server {
    listen 80;
    server_name www.longxuan.vip;
    location / {
        root /data/nginx/html/pc;
    }
    location /abc {
        #必须要在html目录中创建一个名为abc的目录才可以访问,否则报错。
        root /opt/html;                                      
    }
}

[root@sz-kx-centos8 ~]# mkdir -p /opt/html/abc
[root@sz-kx-centos8 ~]# echo /opt/html/abc/index.html > /opt/html/abc/index.html

#检查语法
[root@sz-kx-centos8 ~]# nginx -t
nginx: the configuration file /apps/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /apps/nginx/conf/nginx.conf test is successful

#重新加载nginx
[root@sz-kx-centos8 ~]# nginx -s reload
#访问测试
[root@localhost ~]# curl www.longxuan.vip/abc/
/opt/html/abc/index.html

alias:定义路径别名,会把访问的路径重新定义到其指定的路径,文档映射的另一种机制;仅能用于location上下文,此指令使用较少

范例:

[root@sz-kx-centos8 ~]# vim /apps/nginx/conf/conf.d/pc.conf
server {
    listen 80;
    server_name www.longxuan.vip;
    location / {
        root /data/nginx/html/pc;
    }
    #注意abct后不要加/ , 使用alias的时候uri后面如果加了斜杠,则下面的路径
配置必须加斜杠,否则403
    location /acc {
        #当访问acc的时候,会显示alias定义的/opt/html/abb里面的内容。
        alias /opt/html/abb;                                 
    }
}

#访问测试
[root@localhost ~]# curl www.longxuan.vip/acc/
/opt/html/abb/index.html

范例

[root@centos8 ~]# cat /apps/nginx/conf/conf.d/pc.conf
server {
    listen 80;
    server_name www.longxuan.vip;
    location / {
        root /data/nginx/html/pc;
    }
    location /abc {
        root /opt/html;
    }
    location /acc {
       alias /opt/html/abb;
    }
}
[root@centos8 ~]# ll /opt/html/
total 0
drwxr-xr-x 2 root root 24 Jun 12 06:08 abb
drwxr-xr-x 2 root root 24 Jun 12 06:05 abc
[06:11:31 root@centos8 ~]# tree /opt/html/
/opt/html/
├── abb
│   └── index.html
└── abc
    └── index.html

2 directories, 2 files

# 注意:测试访问后面必须要加上/,不然报错提示301永久重定向
[root@localhost ~]# curl www.longxuan.vip/abc/
/opt/html/abc/index.html

[root@localhost ~]# curl www.longxuan.vip/acc/
/opt/html/abb/index.html

注意:location中使用root指令和alias指令的意义不同

root 给定的路径对应于location中的/uri 左侧的/
alias 给定的路径对应于location中的/uri 的完整路径

location 的详细使用

在一个server中location配置段可存在多个,用于实现从uri到文件系统的路径映射;ngnix会根据用户请
求的URI来检查定义的所有location,按一定的优先级找出一个最佳匹配,而后应用其配置
在没有使用正则表达式的时候,nginx会先在server中的多个location选取匹配度最高的一个uri,uri是
用户请求的字符串,即域名后面的web文件路径,然后使用该location模块中的正则url和字符串,如果
匹配成功就结束搜索,并使用此location处理此请求。

location 官方帮助:

http://nginx.org/en/docs/http/ngx_http_core_module.html#location

语法规则:

location [ = | ~ | ~* | ^~ ] uri { ... }
= #用于标准uri前,需要请求字串与uri精确匹配,大小敏感,如果匹配成功就停止向下匹配并立即处理请
求
^~ #用于标准uri前,表示包含正则表达式,并且匹配以指定的正则表达式开头,对uri的最左边部分做匹配
检查,不区分字符大小写
~ #用于标准uri前,表示包含正则表达式,并且区分大小写
~* #用于标准uri前,表示包含正则表达式,并且不区分大写
不带符号 #匹配起始于此uri的所有的uri
 #用于标准uri前,表示包含正则表达式并且转义字符。可以将 . * ?等转义为普通符号
#匹配优先级从高到低:
=, ^~, ~/~*, 不带符号

官方范例

location = / {
[ configuration A ]
}
location / {
[ configuration B ]
}
location /documents/ {
[ configuration C ]
}
location ^~ /images/ {
[ configuration D ]
}
location ~* .(gif|jpg|jpeg)$ {
[ configuration E ]
}
The “/” request will match configuration A(?), the “/index.html” request will
match configuration B,
the “/documents/document.html” request will match configuration C, the
“/images/1.gif” request will match configuration D, and the “/documents/1.jpg”
request will match configuration E.

匹配案例-精确匹配

在server部分使用location配置一个web界面,例如:当访问nginx 服务器的/logo.jpg的时候要显示指定
html文件的内容
精确匹配一般用于匹配组织的logo等相对固定的URL,匹配优先级最高

范例: 精确匹配 logo

[root@centos8 ~]# mkdir /data/nginx/images -p

[root@centos8 ~]# cat /apps/nginx/conf/conf.d/pc.conf
server {
    listen 80;
    server_name www.longxuan.vip;
    location / {
        root /data/nginx/html/pc;
    }
    location = /log.jpg {
        root /data/nginx/images;
        #index index.html;
    }
}

[root@centos8 ~]# ll /data/nginx/images/
-rw-r--r-- 1 root root 73737 Jun 12 17:57 log.jpg

wind系统图形界面访问测试
http://www.longxuan.vip/log.jpg

匹配案例-区分大小写

~ 实现区分大小写的模糊匹配. 以下范例中, 如果访问uri中包含大写字母的JPG,则以下location匹配
Ax.jpg条件不成功,因为 ~ 区分大小写,当用户的请求被执行匹配时发现location中定义的是小写的
jpg,本次访问的uri匹配失败,后续要么继续往下匹配其他的location(如果有),要么报错给客户端

[root@centos8 ~]# cat /apps/nginx/conf/conf.d/pc.conf
server {
    listen 80;
    server_name www.longxuan.vip;
    location / {
        root /data/nginx/html/pc;
    }
    location ~ /L.?.jpg {
        root /data/nginx/images;
        index index.html;
    }
}

[root@centos8 ~]# ll /data/nginx/images/
-rw-r--r-- 1 root root 73737 Jun 12 17:57 L.jpg
win系统图形界面访问测试
http://www.longxuan.vip/L.jpg

匹配案例-不区分大小写

~* 用来对用户请求的uri做模糊匹配,uri中无论都是大写、都是小写或者大小写混合,此模式也都会匹
配,通常使用此模式匹配用户request中的静态资源并继续做下一步操作,此方式使用较多
注意: 此方式中,对于Linux文件系统上的文件仍然是区分大小写的,如果磁盘文件不存在,仍会提示404

[root@centos8 ~]# cat /apps/nginx/conf/conf.d/pc.conf
server {
    listen 80;
    server_name www.longxuan.vip;
    location / {
        root /data/nginx/html/pc;
    }
    location ~* /L.?.jpg {
        root /data/nginx/images;
        index index.html;
    }
}

[root@centos8 ~]# ll /data/nginx/images/
-rw-r--r-- 1 root root 73737 Jun 12 17:57 l.jpg

#重启Nginx并访问测试
对于不区分大小写的location,则可以访问任意大小写结尾的图片文件,如区分大小写则只能访问La.jpg此
类文件,不区分大小写则可以访问除了la.jpg以外,还有其它的资源比如La.JPG、aL.jPG这样的混合名称文
件,但是还同时也要求nginx服务器的资源目录有相应的文件,比如:必须有La.JPG,aL.jPG这样文件存在。

匹配案例-URI开始

[root@centos8 ~]# mkdir /data/nginx/api -p
[root@centos8 ~]# echo long api web > /data/nginx/api/index.html

[root@centos8 ~]# echo long images > /data/nginx/images/index.html

[root@centos8 ~]# cat /apps/nginx/conf/conf.d/pc.conf
server {
    listen 80;
    server_name www.longxuan.vip;
    location / {
        root /data/nginx/html/pc;
    }
    location ^~ /images {
        root /data/nginx/;
        index index.html;
    }
    location /api {
        alias /data/nginx/api;
    }
}

#测试
[root@localhost ~]# curl http://www.longxuan.vip/images/
long images
[root@localhost ~]# curl http://www.longxuan.vip/api/
long api web

匹配案例-文件名后缀

[root@centos8 ~]# mkdir /data/nginx/static -p
#上传一个图片到/data/nginx/static
[root@centos8 ~]# cat /apps/nginx/conf/conf.d/pc.conf
server {
    listen 80;
    server_name www.longxuan.vip;
    location ~* .(gif|jpg|jpep|png|bmp|tiff|tif|ico|js|css)$ {
        root /data/nginx/static/;
    }
}

[root@centos8 ~]# ll /data/nginx/static/
-rw-r--r-- 1 root root 89032 Jun 12 18:31 aa.png

访问测试
http://www.longxuan.vip/aa.png

匹配案例-优先级

[root@centos8 ~]# mkdir /data/nginx/static{1,2,3} -p
#上传图片到 /data/nginx/static{1,2,3} 并重启nginx访问测试

[18:48:45 root@centos8 ~]# cat /apps/nginx/conf/conf.d/pc.conf
server {
    listen 80;
    server_name www.longxuan.vip;
    location = /1.jpg {
        root /data/nginx/static1;
    }
    location /1.jpg {
        root /data/nginx/static2;
    }
    location ~* .(gif|jpg|jpep|png|bmp|tiff|tif|ico|js|css)$ {
        root /data/nginx/static3;
    }
}

[18:48:54 root@centos8 ~]# tree /data/nginx/
/data/nginx/
├── static1
│   └── 1.jpg
├── static2
│   └── 1.jpg
└── static3
    └── 1.jpg

6 directories, 6 files

#匹配优先级:=, ^~, ~/~*,/
location优先级:(location =) > (location ^~ 路径) > (location ~,~* 正则顺序) >
(location 完整路径) > (location 部分起始路径) > (/)

生产使用案例

#直接匹配网站根会加速Nginx访问处理
location = /index.html {
    ......;
}
location / {
    ......;
}
#静态资源配置方法1
location ^~ /static/ {
    ......;
}
#静态资源配置方法2,应用较多
location ~* .(gif|jpg|jpeg|png|css|js|ico)$ {
    ......;
}
#多应用配置
location ~* /app1 {
    ......;
}
location ~* /app2 {
    ......;
}

Nginx 四层访问控制

访问控制基于模块ngx_http_access_module实现,可以通过匹配客户端源IP地址进行限制
注意: 如果能在防火墙设备控制,最好就不要在nginx上配置,可以更好的节约资源

官方帮助:

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

范例:

location = /login/ {
    root /data/nginx/html/pc;
    allow 10.0.0.0/24;
    deny all;
}
location /about {
    alias /data/nginx/html/pc;
    index index.html;
    deny 192.168.1.1;
    allow 192.168.1.0/24;
    allow 10.1.1.0/16;
    allow 2001:0db8::/32;
    deny all; #按先小范围到大范围排序
}

Nginx 账户认证功能

由 ngx_http_auth_basic_module 模块提供此功能
官方帮助:

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

范例:

#CentOS安装包
[root@centos8 ~]# yum -y install httpd-tools
#Ubuntu安装包
[root@Ubuntu ~]# apt -y install apache2-utils

#创建用户
#-b 非交互式方式提交密码(注意:第一使用-c参数,第二次或者之后的都不能使用了,不然就会覆盖原来的)
[root@centos8 ~]# htpasswd -cb /apps/nginx/conf/.htpasswd user1 123456
Adding password for user user1
[root@centos8 ~]# htpasswd -b /apps/nginx/conf/.htpasswd user2 123456
Adding password for user user2
[root@centos8 ~]# tail /apps/nginx/conf/.htpasswd
user1:$apr1$Rjm0u2Kr$VHvkAIc5OYg.3ZoaGwaGq/
user2:$apr1$nIqnxoJB$LR9W1DTJT.viDJhXa6wHv.
[root@centos8 ~]# vim /apps/nginx/conf/conf.d/pc.conf
server{
    listen 80;
    server_name www.longxuan.vip;
    location = /login/ {
       root /data/nginx/html/pc;
       index index.html;
       auth_basic "login password";
       auth_basic_user_file /apps/nginx/conf/.htpasswd;
    }
}

#重启Nginx并访问测试
[root@centos6 ~]# curl http://user1:123456@www.longxuan.vip/login/
login page
[root@centos6 ~]# curl -u user2:123456 www.longxuan.vip/login/
login page

自定义错误页面

自 定义错误页,同时也可以用指定的响应状态码进行响应, 可用位置:http, server, location, if in location

error_page code ... [=[response]] uri;

范例:

server{
    listen 80;
    server_name www.loongxuan.vip;
    error_page 500 502 503 504 /error.html;
    location = /error.html {
        root /data/nginx/html;
    }
}

#重启nginx并访问不存在的页面进行测试

范例: 自定义错误页面

server{
    listen 80;
    server_name www.loongxuan.vip;
    error_page 404 /40x.html;
    location = /40x.html {
        root /data/html/ ;
    }
}

范例: 如果404,就转到主页

server{
    listen 80;
    server_name www.loongxuan.vip;
    #404转为302
    #error_page 404 /index.html;
    error_page 404 =302 /index.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
    }
}

自定义错误日志

可以自定义错误日志

Syntax: error_log file [level];
Default:
error_log logs/error.log error;
Context: main, http, mail, stream, server, location
level: debug, info, notice, warn, error, crit, alert, emerg

范例:

[root@centos8 ~]# mkdir /data/nginx/logs -p

[19:11:36 root@centos8 ~]# cat /apps/nginx/conf/conf.d/pc.conf
server {
    listen 80;
    server_name www.longxuan.vip;
    error_page 500 502 503 504 404 /error.html;
    access_log /apps/nginx/logs/longxuan-access.log;
    error_log /apps/nginx/logs/longxuan-error.log;
    location = /error.html {
        root html;
    }
}

#重启nginx并访问不存在的页面进行测试并验证是在指定目录生成新的日志文件

检测文件是否存在

try_files会按顺序检查文件是否存在,返回第一个找到的文件或文件夹(结尾加斜线表示为文件夹),如
果所有文件或文件夹都找不到,会进行一个内部重定向到最后一个参数。只有最后一个参数可以引起一
个内部重定向,之前的参数只设置内部URI的指向。最后一个参数是回退URI且必须存在,否则会出现内部500错误。

语法格式

Syntax: try_files file ... uri;
try_files file ... =code;
Default: —
Context: server, location

范例: 如果不存在页面, 就转到default.html页面

[root@centos8 ~]# mkdir -p /data/nginx/html/pc/about/
[root@centos8 ~]# echo "default page" > /data/nginx/html/pc/about/default.html

[root@centos8 ~]# cat /apps/nginx/conf/conf.d/pc.conf
server {
    listen 80;
    server_name www.longxuan.vip;

    location / {
       root /data/nginx/html/pc;
       try_files $uri $uri./index.html /about/default.html;
    }
}

#重启nginx并测试,当访问到http://www.longxuan.vip/about/xx.html等不存在的uri会显示default.html,如果是自定义的状态码则会显示在返回数据的状态码中
[root@localhost ~]# curl http://www.longxuan.vip/sss.html
default page
[root@localhost ~]# curl http://www.longxuan.vip/about/sss.html
default page

#注释default.html行,启用上面998响应码的那一行,在其生效后再观察结果
[root@centos8 ~]# cat /apps/nginx/conf/conf.d/pc.conf
server {
    listen 80;
    server_name www.longxuan.vip;

    location / {
       root /data/nginx/html/pc;
       #try_files $uri $uri./index.html /about/default.html;
       try_files $uri $uri/index.html $uri.html =998;
    }
}

[root@localhost ~]# curl -I http://www.longxuan.vip/about/sss.html
HTTP/1.1 998  #998 就是自定义的状态返回码
Server: nginx/1.18.0
Date: Sat, 12 Jun 2021 11:22:02 GMT
Content-Length: 0
Connection: keep-alive

长连接配置

keepalive_timeout timeout [header_timeout]; #设定保持连接超时时长,0表示禁止长连接,默
认为75s,通常配置在http字段作为站点全局配置
keepalive_requests number; #在一次长连接上所允许请求的资源的最大数量,默认为100次,建议适
当调大,比如:500

范例:

keepalive_requests 3;
keepalive_timeout 65 60;
#开启长连接后,返回客户端的会话保持时间为60s,单次长连接累计请求达到指定次数请求或65秒就会被断
开,第二个数字60为发送给客户端应答报文头部中显示的超时时间设置为60s:如不设置客户端将不显示超时
时间。
Keep-Alive:timeout=60 #浏览器收到的服务器返回的报文
#如果设置为0表示关闭会话保持功能,将如下显示:
Connection:close #浏览器收到的服务器返回的报文
#使用命令测试:
[root@centos8 ~]# telnet www.longxuan.vip 80
...
#页面内容
pc web

作为下载服务器配置

ngx_http_autoindex_module 模块处理以斜杠字符 "/" 结尾的请求,并生成目录列表,可以做为下载服务配置使用

官方文档:

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

相关指令:

autoindex on | off;#自动文件索引功能,默为off
autoindex_exact_size on | off; #计算文件确切大小(单位bytes),off 显示大概大小(单位
K、M),默认on
autoindex_localtime on | off ; #显示本机时间而非GMT(格林威治)时间,默认off
autoindex_format html | xml | json | jsonp; #显示索引的页面文件风格,默认html
limit_rate rate; #限制响应客户端传输速率(除GET和HEAD以外的所有方法),单位B/s,即
bytes/second,默认值0,表示无限制,此指令由ngx_http_core_module提供
set $limit_rate 4k; #也可以通变量限速,单位B/s,同时设置,此项优级高.Rate limit can also
be set in the $limit_rate variable, however, since version 1.17.0, this method is
not recommended:

范例: 实现下载站点

#注意:download不需要index.html文件
[root@centos8 ~]# mkdir -p /data/nginx/html/pc/download
[root@centos8 ~]# vim /apps/nginx/conf/conf.d/pc.conf
location /download {
autoindex on; #自动索引功能
autoindex_exact_size on; #计算文件确切大小(单位bytes),此为默认值,off只显示大概大
小(单位kb、mb、gb)
autoindex_localtime on; #on表示显示本机时间而非GMT(格林威治)时间,默为为off显示GMT时间
limit_rate 1024k; #限速,默认不限速
root /data/nginx/html/pc;
}
[root@centos8 ~]# cp /root/anaconda-ks.cfg /data/nginx/html/pc/download/
#重启Nginx并访问测试下载页面

作为上传服务器

以下指令控制上传数据

client_max_body_size 1m; #设置允许客户端上传单个文件的最大值,默认值为1m,上传文件超过此值会
出413错误
client_body_buffer_size size; #用于接收每个客户端请求报文的body部分的缓冲区大小;默认
16k;超出此大小时,其将被暂存到磁盘上的由client_body_temp_path指令所定义的位置
client_body_temp_path path [level1 [level2 [level3]]];
#设定存储客户端请求报文的body部分的临时存储路径及子目录结构和数量,目录名为16进制的数字,使用
hash之后的值从后往前截取1位、2位、2位作为目录名
[root@centos8 ~]# md5sum /data/nginx/html/pc/index.html
95f6f65f498c74938064851b1bb 96 3d 4 /data/nginx/html/pc/index.html
1级目录占1位16进制,即2^4=16个目录 0-f
2级目录占2位16进制,即2^8=256个目录 00-ff
3级目录占2位16进制,即2^8=256个目录 00-ff
#配置示例:
client_max_body_size 100m; #如果太大,上传时会出现下图的413错误,注意:如果php上传,还需要修
改php.ini的相关配置
client_body_buffer_size 1024k;
client_body_temp_path /apps/nginx/client_body_temp/ 1 2 2; #上传时,Nginx会自动创
建相关目录
#上传超过nginx指定client_max_body_size值会出413错误

[root@long-pc ~]# tail /apps/nginx/logs/nginx.access.log
125.41.184.117 - - [27/Sep/2021:00:09:00 +0800] "POST /wp-admin/async-upload.php
HTTP/1.1" 413 578 "http://www.longxuan.vip/wp-admin/post-new.php"
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/85.0.4183.121 Safari/537.36 Edg/85.0.564.63" "-"

#上传文件后,会自动生成相关目录
[root@long-pc ~]# tree /apps/nginx/client_body_temp/
/apps/nginx/client_body_temp/
├── 5
│   └── 00
│       └── 00
└── 6
    └── 00
        └── 00

其他配置

keepalive_disable none | browser ...;
#对哪种浏览器禁用长连接

范例

limit_except method ... { ... },仅用于location
#禁止客户端使用除了指定的请求方法之外的其它方法,如果使用会出现403错误
method:GET, HEAD, POST, PUT, DELETE,MKCOL, COPY, MOVE, OPTIONS, PROPFIND,
PROPPATCH, LOCK, UNLOCK, PATCH
limit_except GET {
allow 192.168.0.0/24;
allow 172.31.0.1;
deny all;
}
#除了GET和HEAD 之外其它方法仅允许192.168.1.0/24网段主机使用
[root@centos8 ~]# mkdir /data/nginx/html/pc/upload
[root@centos8 ~]# echo "upload" > /data/nginx/html/pc/upload/index.html
[root@centos8 ~]# vim /apps/nginx/conf/conf.d/pc.conf
location /upload {
    root /data/nginx/html/pc;
    index index.html;
    limit_except GET {
        allow 172.31.0.6;
        deny all;
    }
}
#重启Nginx并进行测试上传文件
[root@centos8 ~]# systemctl restart nginx
[root@centos8 ~]#
[root@centos6 ~]# curl -XPUT /etc/issue http://www.longxuan.vip/about
curl: (3) <url> malformed
<html>
<head><title>405 Not Allowed</title></head> #Nginx已经允许,但是程序未支持上传功能
<body bgcolor="white">
<center><h1>405 Not Allowed</h1></center>
<hr><center>nginx</center>
</body>
</html>
[root@centos8 ~]# curl -XPUT /etc/issue http://www.longxuan.vip/upload
curl: (3) <url> malformed
<html>
<head><title>403 Forbidden</title></head> #Nginx拒绝上传
...

aio on | off #是否启用asynchronous file I/O(AIO)功能,需要编译开启 --with-file-aio
#linux 2.6以上内核提供以下几个系统调用来支持aio:
1、SYS_io_setup:建立aio 的context
2、SYS_io_submit: 提交I/O操作请求
3、SYS_io_getevents:获取已完成的I/O事件
4、SYS_io_cancel:取消I/O操作请求
5、SYS_io_destroy:毁销aio的context

directio size | off; #操作完全和aio相反,aio是读取文件而directio是写文件到磁盘,启用直接
I/O,默认为关闭,当文件大于等于给定大小时,例如:directio 4m,同步(直接)写磁盘,而非写缓存。

open_file_cache off; #是否缓存打开过的文件信息
open_file_cache max=N [inactive=time];
#nginx可以缓存以下三种信息:
(1) 文件元数据:文件的描述符、文件大小和最近一次的修改时间
(2) 打开的目录结构
(3) 没有找到的或者没有权限访问的文件的相关信息
max=N:#可缓存的缓存项上限数量;达到上限后会使用LRU(Least recently used,最近最少使用)算法实
现管理
inactive=time:#缓存项的非活动时长,在此处指定的时长内未被命中的或命中的次数少于
open_file_cache_min_uses指令所指定的次数的缓存项即为非活动项,将被删除
open_file_cache_valid time; #缓存项有效性的检查验证频率,默认值为60s
open_file_cache_errors on | off; #是否缓存查找时发生错误的文件一类的信息,默认值为off
open_file_cache_min_uses number; #open_file_cache指令的inactive参数指定的时长内,至少
被命中此处指定的次数方可被归类为活动项,默认值为1

范例:

open_file_cache max=10000 inactive=60s; #最大缓存10000个文件,非活动数据超时时长60s
open_file_cache_valid 60s; #每间隔60s检查一下缓存数据有效性
open_file_cache_min_uses 5; #60秒内至少被命中访问5次才被标记为活动数据
open_file_cache_errors on; #缓存错误信息
原文地址:https://www.cnblogs.com/xuanlv-0413/p/14905035.html