一、 Nginx介绍
特性:
模块化设计,较好的扩展性
高可靠性
支持热部署:不停机更新配置文件,升级版本,更换日志文件
低内存消耗:10000个keep-alive连接模式下的非活动连接,仅需要2.5M内存
基本功能:
静态资源的web服务器
http协议反向代理服务器
pop3/imap4协议反向代理服务器
FastCGI(LNMP),uWSGI(python)等协议
模块化(非DSO),如zip,SSL模块
nginx的程序架构
web服务相关的功能:
虚拟主机(server)
支持 keep-alive 和管道连接
访问日志(支持基于日志缓冲提高其性能)
url rewirte
路径别名
基于IP及用户的访问控制
支持速率限制及并发数限制
重新配置和在线升级而无须中断客户的工作进程
Memcached 的 GET 接口
nginx的程序架构
二、nginx安装
官方:
http://nginx.org/packages/centos/7/x86_64/
Fedora-EPEL:
https://mirrors.aliyun.com/epel/7/x86_64/
[root@centos7 ~]# yum install nginx
[root@centos7 ~]# yum info nginx
已加载插件:fastestmirror, langpacks
Repodata is over 2 weeks old. Install yum-cron? Or run: yum makecache fast
Loading mirror speeds from cached hostfile
已安装的软件包
名称 :nginx
架构 :x86_64
时期 :1
版本 :1.16.1
发布 :1.el7
大小 :1.6 M
源 :installed
来自源:epel
简介 : A high performance web server and reverse proxy server
网址 :http://nginx.org/
协议 : BSD
描述 : Nginx is a web server and a reverse proxy server for HTTP, SMTP, POP3 and
: IMAP protocols, with a strong focus on high concurrency, performance and low
: memory usage.
[root@centos7 ~]# rpm -ql nginx
/etc/logrotate.d/nginx
/etc/nginx/fastcgi.conf
/etc/nginx/fastcgi.conf.default
/etc/nginx/fastcgi_params
/etc/nginx/fastcgi_params.default
/etc/nginx/koi-utf
/etc/nginx/koi-win
/etc/nginx/mime.types
/etc/nginx/mime.types.default
/etc/nginx/nginx.conf
/etc/nginx/nginx.conf.default
/etc/nginx/scgi_params
/etc/nginx/scgi_params.default
/etc/nginx/uwsgi_params
/etc/nginx/uwsgi_params.default
/etc/nginx/win-utf
/usr/bin/nginx-upgrade
/usr/lib/systemd/system/nginx.service
/usr/lib64/nginx/modules
/usr/sbin/nginx
/usr/share/doc/nginx-1.16.1
/usr/share/doc/nginx-1.16.1/CHANGES
/usr/share/doc/nginx-1.16.1/README
/usr/share/doc/nginx-1.16.1/README.dynamic
/usr/share/doc/nginx-1.16.1/UPGRADE-NOTES-1.6-to-1.10
/usr/share/licenses/nginx-1.16.1
/usr/share/licenses/nginx-1.16.1/LICENSE
/usr/share/man/man3/nginx.3pm.gz
/usr/share/man/man8/nginx-upgrade.8.gz
/usr/share/man/man8/nginx.8.gz
/usr/share/nginx/html/404.html
/usr/share/nginx/html/50x.html
/usr/share/nginx/html/en-US
/usr/share/nginx/html/icons
/usr/share/nginx/html/icons/poweredby.png
/usr/share/nginx/html/img
/usr/share/nginx/html/index.html
/usr/share/nginx/html/nginx-logo.png
/usr/share/nginx/html/poweredby.png
/usr/share/vim/vimfiles/ftdetect/nginx.vim
/usr/share/vim/vimfiles/ftplugin/nginx.vim
/usr/share/vim/vimfiles/indent/nginx.vim
/usr/share/vim/vimfiles/syntax/nginx.vim
/var/lib/nginx
/var/lib/nginx/tmp
/var/log/nginx
Nginx启动
默认为启动nginx
[root@centos7 yum.repos.d]# nginx
[root@centos7 yum.repos.d]# ss -ntl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:111 *:*
LISTEN 0 128 *:80 *:*
LISTEN 0 128 *:81 *:*
LISTEN 0 5 192.168.122.1:53 *:*
LISTEN 0 128 *:22 *:*
LISTEN 0 128 127.0.0.1:631 *:*
LISTEN 0 100 127.0.0.1:25 *:*
LISTEN 0 128 127.0.0.1:6011 *:*
LISTEN 0 128 :::111 :::*
LISTEN 0 128 :::80 :::*
LISTEN 0 128 :::22 :::*
LISTEN 0 128 ::1:631 :::*
LISTEN 0 100 ::1:25 :::*
LISTEN 0 128 ::1:6011 :::*
LISTEN 0 80 :::3306 :::*
[root@centos7 ~]# nginx -h
nginx version: nginx/1.16.1
Usage: nginx [-?hvVtTq] [-s signal] [-c filename] [-p prefix] [-g directives]
Options:
-?,-h : this help ##查看帮助选项
-v : show version and exit
-V : show version and configure options then exit ##查看版本和配置选项
-t : test configuration and exit ##测试nginx语法错误
-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
##发送信号给master进程,signal可为:stop, quit, reopen, reload
##示例:-s stop 停止nginx -s reload 加载配置文件
-p prefix : set prefix path (default: /usr/share/nginx/) ##指定页面文件的存放路径
-c filename : set configuration file (default: /etc/nginx/nginx.conf) ##指定配置文件(default: /etc/nginx/nginx.conf)
-g directives : set global directives out of configuration file ## 在命令行中指明全局指令
nginx安装时,默认的编译配置参数
[root@centos7 nginx]# nginx -V
nginx version: nginx/1.16.1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC)
built with OpenSSL 1.0.2k-fips 26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/lib/nginx/tmp/client_body --http-proxy-temp-path=/var/lib/nginx/tmp/proxy --http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi --http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi --http-scgi-temp-path=/var/lib/nginx/tmp/scgi --pid-path=/run/nginx.pid --lock-path=/run/lock/subsys/nginx --user=nginx --group=nginx --with-file-aio --with-ipv6 --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-stream_ssl_preread_module --with-http_addition_module --with-http_xslt_module=dynamic --with-http_image_filter_module=dynamic --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_degradation_module --with-http_slice_module --with-http_stub_status_module --with-http_perl_module=dynamic --with-http_auth_request_module --with-mail=dynamic --with-mail_ssl_module --with-pcre --with-pcre-jit --with-stream=dynamic --with-stream_ssl_module --with-google_perftools_module --with-debug --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -m64 -mtune=generic' --with-ld-opt='-Wl,-z,relro -specs=/usr/lib/rpm/redhat/redhat-hardened-ld -Wl,-E'
配置文件的组成部分:
主配置文件:nginx.conf
子配置文件 include conf.d/*.conf
fastcgi, uwsgi,scgi等协议相关的配置文件
mime.types:支持的mime类型
[root@centos7 nginx]# ls
conf.d fastcgi.conf fastcgi_params koi-utf mime.types nginx.conf nginx.conf.default scgi_params.default uwsgi_params.default
default.d fastcgi.conf.default fastcgi_params.default koi-win mime.types.default scgi_params uwsgi_params win-utf
主配置文件的配置指令
变量
内建变量:由Nginx模块引入,可直接引用
自定义变量:由用户使用set命令定义set variable_name value;
引用变量:$variable_name
注意:
(1) 指令必须以分号结尾
(2) 支持使用配置变量
nginx配置文件
主配置文件结构:四部
main block:主配置段,即全局配置段,对http,mail都有效
event {
...
} 事件驱动相关的配置
http {
...
} http/https 协议相关配置段
mail {
...
} mail 协议相关配置段
stream {
...
} stream 服务器相关配置段
Main 全局配置段常见的配置指令分类
正常运行必备的配置
优化性能相关的配置
用于调试及定位问题相关的配置
事件驱动相关的配置
nginx默认使用的 事件驱动模型是worker模型
[root@centos7 nginx]# ps aux | grep nginx
root 8699 0.0 0.1 118716 2116 ? Ss 13:31 0:00 nginx: master process nginx
nginx 8700 0.0 0.2 121180 3752 ? S 13:31 0:00 nginx: worker process
nginx 8701 0.0 0.2 121180 3744 ? S 13:31 0:00 nginx: worker process
root 11210 0.0 0.0 112676 984 pts/0 R+ 17:16 0:00 grep --color=auto nginx
worker模型是没有开启线程的
[root@centos7 html]# pstree 8699 -p
nginx(8699)─┬─nginx(8700)
└─nginx(8701)
[root@centos7 nginx]# cat nginx.conf
# For more information on configuration, see:
# * Official English Documentation: http://nginx.org/en/docs/
# * Official Russian Documentation: http://nginx.org/ru/docs/
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;
events {
worker_connections 1024;
}
1、user
Syntax: user user [group];
Default: user nobody nobody;
Context: main ##只能放置主配置段中
用于指定worker进程的运行身份,如组不指定,默认和用户名同名
在安装nginx安装包时默认会创建nginx用户
```bash
[root@centos7 nginx]# rpm -q --scripts nginx-filesystem
preinstall scriptlet (using /bin/sh):
getent group nginx > /dev/null || groupadd -r nginx
getent passwd nginx > /dev/null || \
useradd -r -d /var/lib/nginx -g nginx \
-s /sbin/nologin -c "Nginx web server" nginx
exit 0
2、pid /PATH/TO/PID_FILE
指定存储nginx主进程PID的文件路径
注意:不能删除PID文件,会导致无法正常关闭nginx服务, killall nginx才能关闭
Syntax: pid file;
Default: pid logs/nginx.pid;
Context: main
[root@centos7 nginx]# ls /run | grep nginx
nginx.pid
[root@centos7 nginx]# cat /run/nginx.pid
8699 ##8699是master进程的编号
3、include file | mask
指明包含进来的其它配置文件片断
include /usr/share/nginx/modules/*.conf;
4、load_module file
模块加载配置文件:/usr/share/nginx/modules/*.conf
指明要装载的动态模块路径: /usr/lib64/nginx/modules
[root@centos7 nginx]# ls /usr/share/nginx/modules/*.conf;
/usr/share/nginx/modules/mod-http-image-filter.conf /usr/share/nginx/modules/mod-http-xslt-filter.conf /usr/share/nginx/modules/mod-stream.conf
/usr/share/nginx/modules/mod-http-perl.conf /usr/share/nginx/modules/mod-mail.conf
[root@centos7 nginx]# cat /usr/share/nginx/modules/mod-http-perl.conf
load_module "/usr/lib64/nginx/modules/ngx_http_perl_module.so";
性能优化相关的配置:
1、worker_processes number | auto
worker进程的数量;auto通常应该为当前主机的cpu的物理核心数
可以看到worker进程的数量为2个,因为当前主机的CPU物理核心是2核
[root@centos7 nginx]# ps aux | grep nginx
root 8699 0.0 0.1 118716 2116 ? Ss 13:31 0:00 nginx: master process nginx
nginx 8700 0.0 0.2 121180 3752 ? S 13:31 0:00 nginx: worker process
nginx 8701 0.0 0.2 121180 3744 ? S 13:31 0:00 nginx: worker process
2、worker_cpu_affinity cpumask …
worker_cpu_affinity auto [cpumask] 提高缓存命中率
CPU MASK:
00000001:0号CPU
00000010:1号CPU
10000000:8号CPU
worker_cpu_affinity 0001 0010 0100 1000;
worker_cpu_affinity 0101 1010;
使用watch监控nginx的进程工作在哪个cpu上
[root@centos7 html]# watch -n 0.5 'ps axo pid,cmd,psr | grep nginx'
此时客户端使用ab命令测试
[root@centos7 ~]# ab -c 100 -n 1000 http://192.168.239.128/
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking 192.168.239.128 (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests
Server Software: nginx/1.16.1
Server Hostname: 192.168.239.128
Server Port: 80
Document Path: /
Document Length: 4833 bytes
Concurrency Level: 100
Time taken for tests: 0.122 seconds
Complete requests: 1000
Failed requests: 0
Write errors: 0
Total transferred: 5068000 bytes
HTML transferred: 4833000 bytes
Requests per second: 8191.48 [#/sec] (mean)
Time per request: 12.208 [ms] (mean)
Time per request: 0.122 [ms] (mean, across all concurrent requests)
Transfer rate: 40541.45 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 3 3.5 2 16
Processing: 1 8 6.6 6 43
Waiting: 0 7 5.4 5 32
Total: 4 11 7.3 10 44
Percentage of the requests served within a certain time (ms)
50% 10
66% 14
75% 16
80% 17
90% 21
95% 24
98% 32
99% 37
100% 44 (longest request)
测试后,监控发现worker进程并不是固定工作在某个cpu上
这里可以把worker绑定在某个cpu进程上
[root@centos7 nginx]# vim nginx.conf
worker_cpu_affinity 0001; ##绑定在第0颗CPU上
##重新加载
[root@centos7 nginx]# nginx -s reload
ps查看进程,发现此时nginx进程都跑在了第0颗CPU上了,无论多大的并发访问,始终绑定在第0颗CPU上
[root@centos7 nginx]# ps axo pid,cmd,psr | grep nginx
8699 nginx: master process nginx 1
16580 nginx: worker process 0
16581 nginx: worker process 0
16585 grep --color=auto nginx 0
3、worker_priority number
指定worker进程的nice值,设定worker进程优先级:[-20,19]
默认的优先级是0
[root@centos7 nginx]# ps axo pid,cmd,psr,nice | grep nginx
8699 nginx: master process nginx 1 0
16580 nginx: worker process 0 0
16581 nginx: worker process 0 0
17177 grep --color=auto nginx 0 0
调整优先级,调整为-10
worker_priority -10;
[root@centos7 nginx]# ps axo pid,cmd,psr,nice | grep nginx
8699 nginx: master process nginx 1 0
17572 nginx: worker process 0 -10
17573 nginx: worker process 0 -10
17575 grep --color=auto nginx 1 0
4、worker_rlimit_nofile number
worker进程所能够打开的文件数量上限,如65535
事件驱动相关的配置:
events {
...
}
1、worker_connections number
每个worker进程所能够打开的最大并发连接数数量,如10240。默认1024
总最大并发数:worker_processes * worker_connections
Syntax: worker_connections number;
Default:
worker_connections 512;
Context: events
2、use method
指明并发连接请求的处理方法,默认自动选择最优方法
use epoll; ##默认使用epoll
Syntax: use method;
Default: —
Context: events
3、accept_mutex on | off 互斥
处理新的连接请求的方法;on指由各个worker轮流处理新请求,Off指每个新请求的到达都会通知(唤醒)所有的worker进程,但
只有一个进程可获得连接,造成“惊群”,影响性能。
Syntax: accept_mutex on | off;
Default:
accept_mutex off;
Context: events
调试和定位问题:
1、daemon on|off
是否以守护进程方式运行nignx,默认是守护进程方式
Syntax: daemon on | off;
Default:
daemon on;
Context: main
2、master_process on|off
是否以master/worker模型运行nginx;默认为on,off 将不启动worker
Syntax: master_process on | off;
Default:
master_process on;
Context: main
3、error_log file [level]
错误日志文件及其级别;出于调试需要,可设定为debug;但debug仅在编译时使用了“–with-debug”选项时才有效
方式:file /path/logfile;
stderr:发送到标准错误
syslog:server-address[,parameter=values]:发送到syslog服务器
memory:size 内存
level:debug|info|notice|warn|error|crit|alter|emerg
Syntax: error_log file [level];
Default:
error_log logs/error.log error;
Context: main, http, mail, stream, server, location
error_log /var/log/nginx/error.log;
http协议相关的配置结构
http {
...
... 各server的公共配置
server { 每个server用于定义一个虚拟主机
...
}
server {
...
server_name 虚拟主机名
root 主目录
alias 路径别名
location [OPERATOR] URL { 指定URL的特性
...
if CONDITION {
...
} } } }
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 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
include /etc/nginx/conf.d/*.conf;
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
root /usr/share/nginx/html;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
}
error_page 404 /404.html;
location = /404.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
}
ngx_http_core_module
与套接字相关的配置:
1、 server { … }
配置一个虚拟主机
server {
listen address[:PORT]|PORT;
server_name SERVER_NAME;
root /PATH/TO/DOCUMENT_ROOT;
}
进入/etc/nginx/conf.d目录,然后创建虚拟主机
[root@centos7 conf.d]# vim a.com.conf
server {
listen 80;
server_name www.a.com;
root /data/sitea/;
}
[root@centos7 conf.d]# vim b.com.conf
server {
listen 81;
server_name www.b.com;
root /data/siteb/;
}
创建虚拟主机的工作目录
[root@centos7 conf.d]# mkdir -pv /data/site{a,b}
mkdir: created directory ‘/data’
mkdir: created directory ‘/data/sitea’
mkdir: created directory ‘/data/siteb
[root@centos7 conf.d]# echo www.a.com >/data/sitea/index.html
[root@centos7 conf.d]# echo www.b.com >/data/siteb/index.html
客户端测试
[root@centos7 ~]# cat /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 centos7.cwj.com
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.147.135 www.a.com www.b.com
[root@centos7 ~]# curl www.a.com
www.a.com
[root@centos7 ~]# curl www.b.com:81
www.b.com
2、server_tokens on | off | build | string
是否在响应报文的Server首部显示nginx版本
Syntax: server_tokens on | off | build | string;
Default:
server_tokens on;
Context: http, server, location
显示版本信息
server_tokens on;
显示具体版本信息
[root@centos7 ~]# curl -I www.a.com
HTTP/1.1 200 OK
Server: nginx/1.16.1
Date: Thu, 22 Oct 2020 03:04:39 GMT
Content-Type: text/html
Content-Length: 10
Last-Modified: Wed, 21 Oct 2020 04:52:28 GMT
Connection: keep-alive
ETag: "5f8fbe8c-a"
Accept-Ranges: bytes
隐藏版本信息
server_tokens off;
测试,此时只显示nginx
[root@centos7 ~]# curl -I www.a.com
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 22 Oct 2020 02:58:46 GMT
Content-Type: text/html
Content-Length: 10
Last-Modified: Wed, 21 Oct 2020 04:52:28 GMT
Connection: keep-alive
ETag: "5f8fbe8c-a"
Accept-Ranges: bytes
定义路径相关的配置
3、 root
设置web资源的路径映射;用于指明请求的URL所对应的文档的目录路径。
Syntax: root path;
Default:
root html;
Context: http, server, location, if in location
示例
server {
listen 80;
server_name www.a.com;
root /data/sitea/;
}
[root@centos7 conf.d]# ls /data/sitea/image/
day.jpg
访问http://www.a.com/image/day.jpg–> /data/sitea/image/day.jpg
4、 location
location [ = | ~ | ~* | ^~ ] uri { … }
location @name { … }
在一个server中location配置段可存在多个,用于实现从uri到文件系统的路径映射; ngnix会根据用户请求的URI来检查定义的所有location,并找出一个最佳匹配,而后应用其配置
示例:
server {
listen 80;
server_name www.a.com;
root /data/sitea/;
location /news {
root /data/web/;
}
}
[root@centos7 conf.d]# mkdir /data/web/news
[root@centos7 conf.d]# echo "news page" > /data/web/news/index.html
访问:http://www.a.com/news/index.html–> /data/web/news/index.html
=:对URI做精确匹配
server {
listen 80;
server_name www.a.com;
root /data/sitea/;
location /news {
root /data/web/;
}
location = /sports/index.html {
root /data/web/;
}
}
[root@centos7 nginx]# mkdir /data/web/sports
[root@centos7 nginx]# echo "sports page" >> /data/web/sports/index.html
URI输入www.a.com/sports/显示无法访问
http://www.a.com/sports/不匹配
URI输入www.a.com/sports/index.html显示正常访问。
http://www.a.com/sports/index.html 匹配
^~:对URI的最左边部分做匹配检查,不区分字符大小写
~:对URI做正则表达式模式匹配,区分字符大小写
~*:对URI做正则表达式模式匹配,不区分字符大小写
不带符号:匹配起始于此uri的所有的uri
匹配优先级从高到低:
=, ^~, ~ /~ *, 不带符号
注意:location的优先级比root的优先级高
server {
listen 80;
server_name www.a.com;
root /data/sitea/;
location /news {
root /data/web/;
}
location / {
root /data/web/sports/;
}
}
此时访问//www.a.com/,访问的路径是 /data/web/sports/index.html,而不是/data/sitea/index.html
http://www.a.com/–> /data/web/sports/index.html
5、 alias path;
路径别名,文档映射的另一种机制;仅能用于location上下文
Syntax: alias path;
Default: —
Context: location
示例:
访问 http://www.c.com/bbs/index.html则访问的是 /data/web/forum/index.html
http://www.c.com/bbs/index.html
location /bbs/ {
alias /data/web/forum/;
} --> /data/web/forum/index.html
[root@centos7 conf.d]# cat c.com.conf
server {
listen 82;
server_name www.c.com;
root /data/sitec/;
location /bbs {
alias /data/web/forum/;
}
}
[root@centos7 nginx]# mkdir /data/web/forum/
[root@centos7 nginx]# echo "forum page" >> /data/web/forum/index.html
若location中是root,则访问 http://www.c.com/bbs/index.html,则访问的是 /data/web/forum/bbs/index.html
http://www.c.com/bbs/index.html
location /bbs/ {
root /data/web/forum/;
} --> /data/web/forum/bbs/index.html
server {
listen 82;
server_name www.c.com;
root /data/sitec/;
location /bbs {
#alias /data/web/forum/;
root /data/web/forum/;
}
}
[root@centos7 nginx]# mkdir /data/web/forum/bbs
[root@centos7 nginx]# echo "BBS page" >> /data/web/forum/bbs/index.html
6、 error_page
模块: ngx_http_core_module
定义错误页, 以指定的响应状态码进行响应
Syntax: error_page code ... [=[response]] uri;
Default: —
Context: http, server, location, if in location
示例:
error_page 404 /404.html
error_page 404 =200 /404.html ##避免错误页面被劫持
[root@centos7 nginx]# mkdir /data/sitea/error/
[root@centos7 nginx]# echo "error page" >> /data/sitea/error/404.html
[root@centos7 conf.d]# cat a.com.conf
server {
listen 80;
server_name www.a.com;
root /data/sitea/;
error_page 404 /404.html;
location /404.html {
root /data/sitea/error/;
}
location /news {
root /data/web/;
}
location = /sports/index.html {
root /data/web/;
}
}
在360浏览器错误页面劫持。
我们可以把错误响应码重定向到200,这样可以避免错误页面被劫持。
server {
listen 80;
server_name www.a.com;
root /data/sitea/;
error_page 404 =200 /404.html;
location /404.html {
root /data/sitea/error/;
}
location /news {
root /data/web/;
}
location = /sports/index.html {
root /data/web/;
}
}
这样再次使用360浏览器访问时就不会被劫持了。
7、try_files
Syntax: try_files file ... uri;
try_files file ... =code;
Default: —
Context: server, location
按顺序检查文件是否存在,返回第一个找到的文件或文件夹(结尾加斜线表示为文件夹),如果所有的文件或文件夹都找不到,会进行一个内部重定向到最后一个参数。只有最后一个参数可以引起一个内部重定向,之前
的参数只设置内部URI的指向。最后一个参数是回退URI且必须存在,否则会出现内部500错误。
示例:
$uri:当前请求中的URI
$uri在请求处理期间(例如,进行内部重定向或使用索引文件时), 值可能会更改。
[root@centos7 conf.d]# cat a.com.conf
server {
listen 80;
server_name www.a.com;
root /data/sitea/;
error_page 404 =200 /404.html;
location /404.html {
root /data/sitea/error/;
}
location /images {
#try_files $uri /data/sitea/images/default.jpg;
#try_files $uri default.jpg;
try_files $uri /images/default.jpg; ##是到根目录下的image目录中查找default.jpg
##根目录就是上面root定义的/data/sitea/
}
}
[root@centos7 sitea]# ls /data/sitea/images/
default.jpg morning.jpg
location /images/ {
try_files $uri /images/default.gif;
}
location / {
try_files $uri $uri/index.html $uri.html =404;
}
访问一个不存在的图片页面,则由默认的default.jpg页面响应。
响应码依旧是200
8、client_body_buffer_size size;
用于接收每个客户端请求报文的body部分的缓冲区大小;默认为16k;超出此大小时,其将被暂存到磁盘上的由client_body_temp_path指令所定义的位置
9、 client_body_temp_path path [level1 [level2[level3]]];
设定用于存储客户端请求报文的body部分的临时存储路径及子目录结构和数量目录名为16进制的数字;要存储的数据做哈希运算,根据哈希值来组织目录和数据存放位置
示例:
client_body_temp_path /var/tmp/client_body 1 2 2
1 1级目录占1位16进制,即2^4=16个目录 0-f
2 2级目录占2位16进制,即2^8=256个目录 00-ff
2 3级目录占2位16进制, 即2^8=256个目录 00-ff
10、limit_except method … { … }
仅用于location,限制客户端使用除了指定的请求方法之外的其它方法
示例:
server {
listen 80 default_server;
server_name www.a.com;
root /data/sitea/;
error_page 404 =200 /404.html;
location /404.html {
root /data/sitea/error/;
}
location / {
limit_except GET {
allow 192.168.239.130/32;
deny all; ##除了GET和HEAD 之外其它方法仅允许192.168.239.130主机使用
}
}
}
~
在其他客户端测试
[root@centos7 ~]# curl -XPUT -I http://192.168.239.128/
HTTP/1.1 403 Forbidden
Server: nginx/1.16.1
Date: Sat, 24 Oct 2020 05:33:52 GMT
Content-Type: text/html
Content-Length: 157
Connection: keep-alive
11、ngx_http_access_module模块
实现基于ip的访问控制功能,自上而下检查,一旦匹配,将生效,条件严格的置前
allow address | CIDR | unix: | all;
deny address | CIDR | unix: | all;
http, server, location, limit_except
示例
location / {
allow 192.168.239.1;
deny 192.168.239.130;
}
此时从192.168.239.130上访问被拒绝
[root@centos7 ~]# curl -I www.a.com
HTTP/1.1 403 Forbidden
Server: nginx/1.16.1
Date: Sat, 24 Oct 2020 06:07:04 GMT
Content-Type: text/html
Content-Length: 153
Connection: keep-alive
但从宿主机访问被运行
12、ngx_http_auth_basic_module模块
实现基于用户的访问控制,使用basic机制进行用户认证
auth_basic string | off;
auth_basic_user_file file;
用户口令文件:
1、明文文本:格式name:password:comment
2、加密文本:由htpasswd命令实现
htpasswd命令由httpd-tools所提供
示例:
location /admin {
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/conf.d/nginxpasswd;
}
[root@centos7 conf.d]# pwd
/etc/nginx/conf.d
[root@centos7 conf.d]# htpasswd -cm ./nginxpasswd tom ##首次添加用户需要加-c选项
New password:
Re-type new password:
Adding password for user tom
13、ngx_http_stub_status_module模块
用于输出nginx的基本状态信息
示例:
location /status {
stub_status;
}
}
Active connections:当前状态,活动状态的连接数
accepts:统计总值,已经接受的客户端请求的总数
handled:统计总值,已经处理完成的客户端请求的总数
requests:统计总值,客户端发来的总的请求数
Reading:当前状态,正在读取客户端请求报文首部的连接的连接数
Writing:当前状态,正在向客户端发送响应报文过程中的连接数
Waiting:当前状态,正在等待客户端发出请求的空闲连接数
14、ngx_http_gzip_module
用gzip方法压缩响应数据,节约带宽
1、gzip on | off;
启用或禁用gzip压缩
2、gzip_comp_level level;
压缩比由低到高:1 到 9
默认:1
3、gzip_disable regex …;
匹配到客户端浏览器不执行压缩
4、gzip_min_length length;
启用压缩功能的响应报文大小阈值,以字节为单位
5、gzip_http_version 1.0 | 1.1;
设定启用压缩功能时,协议的最小版本,默认:1.1
6、gzip_buffers number size;
支持实现压缩功能时缓冲区数量及每个缓存区的大小
默认:32 4k 或 16 8k
7、gzip_types mime-type …;
指明仅对哪些类型的资源执行压缩操作;即压缩过滤器,默认包含有text/html,不用显示指定,否则出错
8、gzip_vary on | off;
如果启用压缩,是否在响应报文首部插入“Vary: Accept-Encoding”
9、gzip_proxied off | expired | no-cache | no-store | private | no_last_modified | no_etag | auth | any …;
nginx充当代理服务器时,对于后端服务器的响应报文,在何种条件下启用压缩功能
off:不启用压缩
expired,no-cache, no-store,private:对后端服务器的响应报文首部Cache-Control值任何一个,启用压缩功能
示例:
server {
listen 80 default_server;
server_name www.a.com;
root /data/sitea/;
error_page 404 =200 /404.html;
gzip on;
gzip_comp_level 6;
gzip_min_length 64;
gzip_proxied any;
gzip_types text/xml text/css application/javascript text/plain;
location /404.html {
root /data/sitea/error/;
}
location /status {
stub_status;
}
}