【NGINX入门指北】 基础篇
文章目录
- 一、Nginx 简介
- 1.什么是Nginx?
- 2.Nginx 的作用
- 二、Nginx的安装
- 1.Windows下安装Nginx
- 2.Linux下安装Nginx
- 1、源码编译安装
- 2、yum 安装
- 三、Nginx常用命令
- 四、Nginx的配置文件
- 五、Nginx的编译参数
- 六、nginx的基本配置
- 七、nginx 日志log
- 1、日志配置
- 2、日志轮转/切割
- 3、日志分析
- 八、nginx web 模块
- 九、nginx 访问限制
- 十、nginx 访问控制
一、Nginx 简介
1.什么是Nginx?
Nginx(engine ) 是一个高性能的HTTP(解决C10K(万级并发))和反向代理web服务器,同时也提供了IMAP/POP3/SMTP(邮局)服务。Nginx是由伊戈尔.赛索耶夫为俄罗斯访问量第二的Rambler.ru站点(俄文:Pam6nep)开发的,第一个公开版本0.1.0发布于2004年10月4日,2011年6月1日,Nginx 1.0.4发布。
其特点是占有内存少,并发能力强,事实上Nginx的并发能力在同类的网页服务器中表现较好,中国大陆使用Nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝、等。在全球活跃的网站中有12.18%的使用比率,大约为2220万个网站
Nginx是一个安装非常简单的、配置文件非常简洁(还能够支持perl语法)、bug非常少的服务。Nginx 启动特别容易,并且几乎可以做到7*24不间断运行,即使运行数个月也不需要重新启动,而且还能够不间断服务的情况下进行软件版本的升级。
Nginx 代码完全是用C语言从头写成功。官方数据测试表明能够支持高达50,000个并发连接的响应。
2.Nginx 的作用
Http代理,反向代理:作为web服务器最常用的功能之一,尤其是反向代理。
正向代理:
反向代理:
Nginx提供的负载均衡策略有2种:内置策略和拓展策略。内置策略为轮询,加权轮询,IP hash.拓展策略
轮询:
加权轮询:
iphash对客户端请求的ip进行hash操作,然后根据hash结果将同一个客户端ip的请求分发给同一台服务器进行处理,可以解决session不共享的问题。
动静分离:我们在软件开发中,有些请求是需要后台处理的,有些请求是不需要经过后台处理的(如:css、html、jpg、js等等文件),这些不需要经过后台处理的文件称为静态文件。让动态网站里的动态网页根据一定规则把不变的资源和经常变得资源区分开来,动静资源做好了拆分以后,我们就可以根据静态资源的特点将其做缓存操作,提高资源响应的速度。
目前,通过使用Nginx大大提高了我们网站的响应速度,优化了用户体验,让网站的健壮性更上一层楼!
二、Nginx的安装
1.Windows下安装Nginx
Nginx官网下载地址:http://nginx.org/en/download.html
下载稳定版。
2.Linux下安装Nginx
1、源码编译安装
Nginx官网下载地址:http://nginx.org/en/download.html
下载稳定版。
在浏览器访问检查是否成功启动Nginx
2、yum 安装
[root@node3 ~]# sudo yum install yum-utils
已加载插件:fastestmirror, langpacks
Loading mirror speeds from cached hostfile
Could not retrieve mirrorlist http://mirrors.elrepo.org/mirrors-elrepo.el7 error was
14: curl#7 - "Failed connect to mirrors.elrepo.org:80; 拒绝连接"* base: mirrors.aliyun.com* elrepo: repos.lax-noc.com* extras: mirrors.aliyun.com* updates: mirrors.aliyun.com
Ceph | 1.5 kB 00:00:00
Ceph-noarch | 1.5 kB 00:00:00
base | 3.6 kB 00:00:00
ceph-source | 1.5 kB 00:00:00
elrepo | 3.0 kB 00:00:00
epel | 4.7 kB 00:00:00
extras | 2.9 kB 00:00:00
percona-release-noarch | 1.5 kB 00:00:00
percona-release-x86_64 | 2.9 kB 00:00:00
prel-release-noarch | 1.5 kB 00:00:00
updates | 2.9 kB 00:00:00
zabbix | 2.9 kB 00:00:00
zabbix-frontend | 2.9 kB 00:00:00
zabbix-non-supported | 2.9 kB 00:00:00
软件包 yum-utils-1.1.31-54.el7_8.noarch 已安装并且是最新版本
无须任何处理
配置yum源
[root@node3 ~]# vim /etc/yum.repos.d/nginx.repo
[root@node3 ~]# cat /etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
[root@node3 ~]# sudo yum-config-manager --enable nginx-mainline
已加载插件:fastestmirror, langpacks
======================================== repo: nginx-mainline =========================================
[nginx-mainline]
async = True
bandwidth = 0
base_persistdir = /var/lib/yum/repos/x86_64/7
baseurl = http://nginx.org/packages/mainline/centos/7/x86_64/
cache = 0
cachedir = /var/cache/yum/x86_64/7/nginx-mainline
check_config_file_age = True
compare_providers_priority = 80
cost = 1000
deltarpm_metadata_percentage = 100
deltarpm_percentage =
enabled = 1
enablegroups = True
exclude =
failovermethod = priority
ftp_disable_epsv = False
gpgcadir = /var/lib/yum/repos/x86_64/7/nginx-mainline/gpgcadir
gpgcakey =
gpgcheck = True
gpgdir = /var/lib/yum/repos/x86_64/7/nginx-mainline/gpgdir
gpgkey = https://nginx.org/keys/nginx_signing.key
hdrdir = /var/cache/yum/x86_64/7/nginx-mainline/headers
http_caching = all
includepkgs =
ip_resolve =
keepalive = True
keepcache = False
mddownloadpolicy = sqlite
mdpolicy = group:small
mediaid =
metadata_expire = 21600
metadata_expire_filter = read-only:present
metalink =
minrate = 0
mirrorlist =
mirrorlist_expire = 86400
name = nginx mainline repo
old_base_cache_dir =
password =
persistdir = /var/lib/yum/repos/x86_64/7/nginx-mainline
pkgdir = /var/cache/yum/x86_64/7/nginx-mainline/packages
proxy = False
proxy_dict =
proxy_password =
proxy_username =
repo_gpgcheck = False
retries = 10
skip_if_unavailable = False
ssl_check_cert_permissions = True
sslcacert =
sslclientcert =
sslclientkey =
sslverify = True
throttle = 0
timeout = 30.0
ui_id = nginx-mainline/7/x86_64
ui_repoid_vars = releasever,basearch
username = [root@node3 ~]# cat /etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
[root@node3 ~]# yum makecache
已加载插件:fastestmirror, langpacks
Loading mirror speeds from cached hostfile
Could not retrieve mirrorlist http://mirrors.elrepo.org/mirrors-elrepo.el7 error was
14: curl#7 - "Failed connect to mirrors.elrepo.org:80; 拒绝连接"* base: mirrors.aliyun.com* elrepo: elrepo.org* extras: mirrors.aliyun.com* updates: mirrors.aliyun.com
Ceph | 1.5 kB 00:00:00
Ceph-noarch | 1.5 kB 00:00:00
base | 3.6 kB 00:00:00
ceph-source | 1.5 kB 00:00:00
elrepo | 3.0 kB 00:00:00
epel | 4.7 kB 00:00:00
extras | 2.9 kB 00:00:00
nginx-mainline | 2.9 kB 00:00:00
nginx-stable | 2.9 kB 00:00:00
percona-release-noarch | 1.5 kB 00:00:00
percona-release-x86_64 | 2.9 kB 00:00:00
prel-release-noarch | 1.5 kB 00:00:00
updates | 2.9 kB 00:00:00
zabbix | 2.9 kB 00:00:00
zabbix-frontend | 2.9 kB 00:00:00
zabbix-non-supported | 2.9 kB 00:00:00
(1/24): ceph-source/filelists | 2.3 kB 00:00:06
(2/24): ceph-source/other | 2.4 kB 00:00:06
(3/24): Ceph-noarch/other | 1.3 kB 00:00:06
(4/24): Ceph-noarch/filelists | 25 kB 00:00:06
(5/24): epel/x86_64/prestodelta | 341 B 00:00:00
(6/24): Ceph/x86_64/filelists | 838 kB 00:00:11
(7/24): extras/7/x86_64/filelists_db | 276 kB 00:00:01
(8/24): elrepo/other_db | 36 kB 00:00:06
(9/24): extras/7/x86_64/other_db | 149 kB 00:00:01
(10/24): elrepo/filelists_db | 43 kB 00:00:13
(11/24): nginx-mainline/7/x86_64/primary_db | 250 kB 00:00:11
(12/24): epel/x86_64/other_db | 3.4 MB 00:00:19
(13/24): nginx-mainline/7/x86_64/other_db | 148 kB 00:00:04
(14/24): nginx-stable/7/x86_64/filelists_db | 105 kB 00:00:08
(15/24): nginx-stable/7/x86_64/primary_db | 80 kB 00:00:08
(16/24): nginx-stable/7/x86_64/other_db | 49 kB 00:00:01
(17/24): nginx-mainline/7/x86_64/filelists_db | 327 kB 00:00:23
(18/24): percona-release-noarch/7/filelists | 5.3 kB 00:00:06
(19/24): percona-release-noarch/7/other | 4.6 kB 00:00:06
(20/24): prel-release-noarch/7/filelists | 544 B 00:00:06
(21/24): prel-release-noarch/7/other | 781 B 00:00:06
(22/24): zabbix-non-supported/x86_64/filelists_db | 1.7 kB 00:00:06
(23/24): zabbix-non-supported/x86_64/other_db | 3.3 kB 00:00:06
(24/24): epel/x86_64/filelists_db | 12 MB 00:01:15
Ceph 916/916
Ceph-noarch 19/19
Ceph-noarch 19/19
ceph-source 43/43
ceph-source 43/43
percona-release-noarch 65/65
percona-release-noarch 65/65
prel-release-noarch 5/5
prel-release-noarch 5/5
元数据缓存已建立
[root@node3 ~]# yum list | grep nginx
Could not retrieve mirrorlist http://mirrors.elrepo.org/mirrors-elrepo.el7 error was
14: curl#7 - "Failed connect to mirrors.elrepo.org:80; 拒绝连接"
nginx.x86_64 1:1.20.1-10.el7 @epel
nginx-filesystem.noarch 1:1.20.1-10.el7 @epel
rh-nginx116-nginx.x86_64 1:1.16.1-6.el7 @centos-sclo-rh
rh-nginx116-runtime.x86_64 1.16-1.el7 @centos-sclo-rh
zabbix-nginx-conf-scl.noarch 5.0.28-1.el7 @zabbix-frontend
collectd-nginx.x86_64 5.8.1-1.el7 epel
munin-nginx.noarch 2.0.69-5.el7 epel
nginx.x86_64 1:1.23.3-1.el7.ngx nginx-mainline
nginx-all-modules.noarch 1:1.20.1-10.el7 epel
nginx-debug.x86_64 1:1.9.7-1.el7.ngx nginx-mainline
nginx-debuginfo.x86_64 1:1.23.3-1.el7.ngx nginx-mainline
nginx-mod-devel.x86_64 1:1.20.1-10.el7 epel
nginx-mod-http-image-filter.x86_64 1:1.20.1-10.el7 epel
nginx-mod-http-perl.x86_64 1:1.20.1-10.el7 epel
nginx-mod-http-xslt-filter.x86_64 1:1.20.1-10.el7 epel
nginx-mod-mail.x86_64 1:1.20.1-10.el7 epel
nginx-mod-stream.x86_64 1:1.20.1-10.el7 epel
nginx-module-geoip.x86_64 1:1.23.3-1.el7.ngx nginx-mainline
nginx-module-geoip-debuginfo.x86_64 1:1.23.3-1.el7.ngx nginx-mainline
nginx-module-image-filter.x86_64 1:1.23.3-1.el7.ngx nginx-mainline
nginx-module-image-filter-debuginfo.x86_641:1.23.3-1.el7.ngx nginx-mainline
nginx-module-njs.x86_64 1:1.23.3+0.7.9-1.el7.ngx nginx-mainline
nginx-module-njs-debuginfo.x86_64 1:1.23.3+0.7.9-1.el7.ngx nginx-mainline
nginx-module-perl.x86_64 1:1.23.3-1.el7.ngx nginx-mainline
nginx-module-perl-debuginfo.x86_64 1:1.23.3-1.el7.ngx nginx-mainline
nginx-module-xslt.x86_64 1:1.23.3-1.el7.ngx nginx-mainline
nginx-module-xslt-debuginfo.x86_64 1:1.23.3-1.el7.ngx nginx-mainline
nginx-nr-agent.noarch 2.0.0-12.el7.ngx nginx-mainline
pagure-web-nginx.noarch 5.13.3-2.el7 epel
pcp-pmda-nginx.x86_64 4.3.2-13.el7_9 updates
python2-certbot-nginx.noarch 1.11.0-1.el7 epel
sympa-nginx.x86_64 6.2.70-2.el7 epel
unit.x86_64 0.1-1.el7.ngx nginx-mainline
unit-debuginfo.x86_64 0.1-1.el7.ngx nginx-mainline
unit-devel.x86_64 0.1-1.el7.ngx nginx-mainline
zabbix-nginx-conf-scl.noarch 5.0.31-1.el7 zabbix-frontend
[root@node3 ~]# sudo yum-config-manager --disable nginx-mainline
已加载插件:fastestmirror, langpacks
======================================== repo: nginx-mainline =========================================
[nginx-mainline]
async = True
bandwidth = 0
base_persistdir = /var/lib/yum/repos/x86_64/7
baseurl = http://nginx.org/packages/mainline/centos/7/x86_64/
cache = 0
cachedir = /var/cache/yum/x86_64/7/nginx-mainline
check_config_file_age = True
compare_providers_priority = 80
cost = 1000
deltarpm_metadata_percentage = 100
deltarpm_percentage =
enabled = 0
enablegroups = True
exclude =
failovermethod = priority
ftp_disable_epsv = False
gpgcadir = /var/lib/yum/repos/x86_64/7/nginx-mainline/gpgcadir
gpgcakey =
gpgcheck = True
gpgdir = /var/lib/yum/repos/x86_64/7/nginx-mainline/gpgdir
gpgkey = https://nginx.org/keys/nginx_signing.key
hdrdir = /var/cache/yum/x86_64/7/nginx-mainline/headers
http_caching = all
includepkgs =
ip_resolve =
keepalive = True
keepcache = False
mddownloadpolicy = sqlite
mdpolicy = group:small
mediaid =
metadata_expire = 21600
metadata_expire_filter = read-only:present
metalink =
minrate = 0
mirrorlist =
mirrorlist_expire = 86400
name = nginx mainline repo
old_base_cache_dir =
password =
persistdir = /var/lib/yum/repos/x86_64/7/nginx-mainline
pkgdir = /var/cache/yum/x86_64/7/nginx-mainline/packages
proxy = False
proxy_dict =
proxy_password =
proxy_username =
repo_gpgcheck = False
retries = 10
skip_if_unavailable = False
ssl_check_cert_permissions = True
sslcacert =
sslclientcert =
sslclientkey =
sslverify = True
throttle = 0
timeout = 30.0
ui_id = nginx-mainline/7/x86_64
ui_repoid_vars = releasever,basearch
username = [root@node3 ~]# cat /etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
[root@node3 ~]# yum list | grep nginx
Could not retrieve mirrorlist http://mirrors.elrepo.org/mirrors-elrepo.el7 error was
14: curl#7 - "Failed connect to mirrors.elrepo.org:80; 拒绝连接"
nginx.x86_64 1:1.20.1-10.el7 @epel
nginx-filesystem.noarch 1:1.20.1-10.el7 @epel
rh-nginx116-nginx.x86_64 1:1.16.1-6.el7 @centos-sclo-rh
rh-nginx116-runtime.x86_64 1.16-1.el7 @centos-sclo-rh
zabbix-nginx-conf-scl.noarch 5.0.28-1.el7 @zabbix-frontend
collectd-nginx.x86_64 5.8.1-1.el7 epel
munin-nginx.noarch 2.0.69-5.el7 epel
nginx.x86_64 1:1.22.1-1.el7.ngx nginx-stable
nginx-all-modules.noarch 1:1.20.1-10.el7 epel
nginx-debug.x86_64 1:1.8.0-1.el7.ngx nginx-stable
nginx-debuginfo.x86_64 1:1.22.1-1.el7.ngx nginx-stable
nginx-mod-devel.x86_64 1:1.20.1-10.el7 epel
nginx-mod-http-image-filter.x86_64 1:1.20.1-10.el7 epel
nginx-mod-http-perl.x86_64 1:1.20.1-10.el7 epel
nginx-mod-http-xslt-filter.x86_64 1:1.20.1-10.el7 epel
nginx-mod-mail.x86_64 1:1.20.1-10.el7 epel
nginx-mod-stream.x86_64 1:1.20.1-10.el7 epel
nginx-module-geoip.x86_64 1:1.22.1-1.el7.ngx nginx-stable
nginx-module-geoip-debuginfo.x86_64 1:1.22.1-1.el7.ngx nginx-stable
nginx-module-image-filter.x86_64 1:1.22.1-1.el7.ngx nginx-stable
nginx-module-image-filter-debuginfo.x86_641:1.22.1-1.el7.ngx nginx-stable
nginx-module-njs.x86_64 1:1.22.1+0.7.9-1.el7.ngx nginx-stable
nginx-module-njs-debuginfo.x86_64 1:1.22.1+0.7.9-1.el7.ngx nginx-stable
nginx-module-perl.x86_64 1:1.22.1-1.el7.ngx nginx-stable
nginx-module-perl-debuginfo.x86_64 1:1.22.1-1.el7.ngx nginx-stable
nginx-module-xslt.x86_64 1:1.22.1-1.el7.ngx nginx-stable
nginx-module-xslt-debuginfo.x86_64 1:1.22.1-1.el7.ngx nginx-stable
nginx-nr-agent.noarch 2.0.0-12.el7.ngx nginx-stable
pagure-web-nginx.noarch 5.13.3-2.el7 epel
pcp-pmda-nginx.x86_64 4.3.2-13.el7_9 updates
python2-certbot-nginx.noarch 1.11.0-1.el7 epel
sympa-nginx.x86_64 6.2.70-2.el7 epel
zabbix-nginx-conf-scl.noarch 5.0.31-1.el7 zabbix-frontend
安装nginx
[root@node3 ~]# yum install -y nginx
已加载插件:fastestmirror, langpacks
Loading mirror speeds from cached hostfile
Could not retrieve mirrorlist http://mirrors.elrepo.org/mirrors-elrepo.el7 error was
14: curl#7 - "Failed connect to mirrors.elrepo.org:80; 拒绝连接"* base: mirrors.aliyun.com* elrepo: elrepo.org* extras: mirrors.aliyun.com* updates: mirrors.aliyun.com
nginx-stable | 2.9 kB 00:00:01
正在解决依赖关系
--> 正在检查事务
---> 软件包 nginx.x86_64.1.1.20.1-10.el7 将被 升级
---> 软件包 nginx.x86_64.1.1.22.1-1.el7.ngx 将被 更新
--> 解决依赖关系完成依赖关系解决=======================================================================================================Package 架构 版本 源 大小
=======================================================================================================
正在更新:nginx x86_64 1:1.22.1-1.el7.ngx nginx-stable 797 k事务概要
=======================================================================================================
升级 1 软件包总下载量:797 k
Downloading packages:
No Presto metadata available for nginx-stable
警告:/var/cache/yum/x86_64/7/nginx-stable/packages/nginx-1.22.1-1.el7.ngx.x86_64.rpm: 头V4 RSA/SHA256 Signature, 密钥 ID 7bd9bf62: NOKEY
nginx-1.22.1-1.el7.ngx.x86_64.rpm 的公钥尚未安装
nginx-1.22.1-1.el7.ngx.x86_64.rpm | 797 kB 00:00:35
从 https://nginx.org/keys/nginx_signing.key 检索密钥
导入 GPG key 0x7BD9BF62:用户ID : "nginx signing key <signing-key@nginx.com>"指纹 : 573b fd6b 3d8f bc64 1079 a6ab abf5 bd82 7bd9 bf62来自 : https://nginx.org/keys/nginx_signing.key
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction正在更新 : 1:nginx-1.22.1-1.el7.ngx.x86_64 1/2 清理 : 1:nginx-1.20.1-10.el7.x86_64 2/2 验证中 : 1:nginx-1.22.1-1.el7.ngx.x86_64 1/2 验证中 : 1:nginx-1.20.1-10.el7.x86_64 2/2 更新完毕:nginx.x86_64 1:1.22.1-1.el7.ngx 完毕!
[root@node3 ~]#
三、Nginx常用命令
root@192 nginx-1.22.0]# whereis nginx
nginx: /usr/local/nginx
[root@192 nginx-1.22.0]# cd /usr/local/nginx/sbin
[root@192 sbin]# ls
nginx
[root@192 sbin]#./nginx -v
nginx version: nginx/1.22.0
[root@192 sbin]# ./nginx 启动
[root@192 sbin]# ./nginx -s stop 停止
[root@192 sbin]# ./nginx -s quit 安全退出
[root@192 sbin]# ./nginx -s reload 重新加载配置文件
[root@192 sbin]# ps aux|grep nginx 查看Nginx进程
四、Nginx的配置文件
1.nginx相关的所有的文件
[root@node3 ~]# rpm -ql nginx
/etc/logrotate.d/nginx #日志轮转
/etc/nginx #总配置文件
/etc/nginx/conf.d #子配置文件
/etc/nginx/conf.d/default.conf #默认的网站配置文件
/etc/nginx/fastcgi_params
/etc/nginx/mime.types # 关联程序;网站文件类型和相关处理程序
/etc/nginx/modules # 模块文件,第三方模块
/etc/nginx/nginx.conf
/etc/nginx/scgi_params
/etc/nginx/uwsgi_params
/usr/lib/systemd/system/nginx-debug.service
/usr/lib/systemd/system/nginx.service
/usr/lib64/nginx
/usr/lib64/nginx/modules
/usr/libexec/initscripts/legacy-actions/nginx
/usr/libexec/initscripts/legacy-actions/nginx/check-reload
/usr/libexec/initscripts/legacy-actions/nginx/upgrade
/usr/sbin/nginx # 主程序
/usr/sbin/nginx-debug
/usr/share/doc/nginx-1.22.1
/usr/share/doc/nginx-1.22.1/COPYRIGHT
/usr/share/man/man8/nginx.8.gz
/usr/share/nginx
/usr/share/nginx/html
/usr/share/nginx/html/50x.html
/usr/share/nginx/html/index.html
/var/cache/nginx
/var/log/nginx
[root@node3 ~]#
2.配置文件目录位置
/usr/local/nginx/conf/nginx.conf
3.Nginx的主配置文件
user nginx;
worker_processes auto;error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;events {worker_connections 1024;
}http {include mime.types;default_type application/octet-stream; #字节流处理#log_format main '$remote_addr - $remote_user [$time_local] "$request" '# '$status $body_bytes_sent "$http_referer" '# '"$http_user_agent" "$http_x_forwarded_for"';#access_log logs/access.log main;sendfile on;#tcp_nopush on;#keepalive_timeout 0;keepalive_timeout 65;#gzip on;server {listen 80; #监听端口server_name localhost; # FQDN#charset koi8-r; # 网页字符类型#access_log logs/host.access.log main; # 日志location / {root html;index index.html index.htm;}#error_page 404 /404.html;# redirect server error pages to the static page /50x.html#error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}# proxy the PHP scripts to Apache listening on 127.0.0.1:80##location ~ \.php$ {# proxy_pass http://127.0.0.1;#}# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000##location ~ \.php$ {# root html;# fastcgi_pass 127.0.0.1:9000;# fastcgi_index index.php;# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;# include fastcgi_params;#}# deny access to .htaccess files, if Apache's document root# concurs with nginx's one##location ~ /\.ht {# deny all;#}}# another virtual host using mix of IP-, name-, and port-based configuration##server {# listen 8000;# listen somename:8080;# server_name somename alias another.alias;# location / {# root html;# index index.html index.htm;# }#}# HTTPS server##server {# listen 443 ssl;# server_name localhost;# ssl_certificate cert.pem;# ssl_certificate_key cert.key;# ssl_session_cache shared:SSL:1m;# ssl_session_timeout 5m;# ssl_ciphers HIGH:!aNULL:!MD5;# ssl_prefer_server_ciphers on;# location / {# root html;# index index.html index.htm;# }#}}
3.nginx 主配置文件有三部分组成
第一部分:全局块
从配置文件开始到 events 块之间的内容,主要会设置一些影响nginx 服务器整体运行的配置指令,主要包括配置运行 Nginx 服务器的用户(组)、允许生成的 worker process 数,进程 PID 存放路径、日志存放路径和类型以 及配置文件的引入等。
比如上面第一行配置的:
worker_processes 1;
这是 Nginx 服务器并发处理服务的关键配置,worker_processes 值越大,可以支持的并发处理量也越多,但是 会受到硬件、软件等设备的制约。
第二部分:events块
比如上面的配置:
events {worker_connections 1024;
}
events 块涉及的指令主要影响 Nginx 服务器与用户的网络连接,常用的设置包括是否开启对多 work process 下的网络连接进行序列化,是否 允许同时接收多个网络连接,选取哪种事件驱动模型来处理连接请求,每个 word process 可以同时支持的最大连接数等。
上述例子就表示每个 work process 支持的最大连接数为 1024.
这部分的配置对 Nginx 的性能影响较大,在实际中应该灵活配置
第三部分:
http {include mime.types;default_type application/octet-stream;sendfile on;keepalive_timeout 65;server {listen 80;server_name localhost;location / {root html;index index.html index.htm;}error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}}
}
这算是 Nginx 服务器配置中最频繁的部分,代理、缓存和日志定义等绝大多数功能和第三方模块的配置都在这里。
需要注意的是:http 块也可以包括 http全局块、server 块。
http全局块
http全局块配置的指令包括文件引入、MIME-TYPE 定义、日志自定义、连接超时时间、单链接请求数上限等。
server 块
这块和虚拟主机有密切关系,虚拟主机从用户角度看,和一台独立的硬件主机是完全一样的,该技术的产生是为了 节省互联网服务器硬件成本。
每个 http 块可以包括多个 server 块,而每个 server 块就相当于一个虚拟主机。
而每个 server 块也分为全局 server 块,以及可以同时包含多个 location 块。
全局 server 块
最常见的配置是本虚拟机主机的监听配置和本虚拟主机的名称或IP配置。
location 块
一个 server 块可以配置多个 location 块。
这块的主要作用是基于 Nginx 服务器接收到的请求字符串
五、Nginx的编译参数
[root@node3 ~]# nginx -V
nginx version: nginx/1.22.1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC)
built with OpenSSL 1.0.2k-fips 26 Jan 2017
TLS SNI support enabled
configure arguments: # 配置参数 ./congfigure --help 查询帮助
--prefix=/etc/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 # 访问日志
--pid-path=/var/run/nginx.pid # 程序 ID
--lock-path=/var/run/nginx.lock # 锁路径,防止重复启动nginx
--http-client-body-temp-path=/var/cache/nginx/client_temp # 缓存
--http-proxy-temp-path=/var/cache/nginx/proxy_temp # 代理缓存
--http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp # php缓存
--http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp # Python缓存
--http-scgi-temp-path=/var/cache/nginx/scgi_temp
--user=nginx # 用户
--group=nginx # 组
--with-compat # 启用动态模块兼容性
--with-file-aio
# 使用nginx的aio特性会大大提高性能,比如图片网站的特点是大量的读io操作,nginx的aio不用等待每次io的结果,有助于并发处理大量io和提高nginx处理效率。
#aio的优点就是能够同时提交多个io请求给内核,然后直接由内核的io调度算法去处理这些请求(directio),这样,内核就有可能执行一些合并,节约了读取文件的处理时间。这就是异步非阻塞
--with-threads # 多线程模块
--with-http_addition_module # 响应之前或者之后追加文本内容,比如想在站点1底部追加一个 js广告或者新增的 css 样式
--with-http_auth_request_module # 认证模块
--with-http_dav_module --with-http_flv_module
# 增加上传PUT,DELETE,MKCOL;创建集合,COPY和MOVE方法,默认情况下为关闭
--with-http_gunzip_module # 压缩模块
--with-http_gzip_static_module
--with-http_mp4_module # 多媒体模块
--with-http_random_index_module
--with-http_realip_module # nginx 获取真实 IP 模块
--with-http_secure_link_module # nginx 安全下载模块
--with-http_slice_module # 安全模块
--with-http_ssl_module
--with-http_stub_status_module # 访问状态
--with-http_sub_module # nginx 替换网站响应内容
--with-http_v2_module
--with-mail # 邮件客户端
--with-mail_ssl_module
--with-stream
--with-stream_realip_module
--with-stream_ssl_module
--with-stream_ssl_preread_module
--with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'
[root@node3 ~]#
六、nginx的基本配置
[root@node3 ~]# cat /etc/nginx/conf.d/default.conf
server {listen 80;server_name localhost; # FQDN# 访问日志#access_log /var/log/nginx/host.access.log main; location / {root /usr/share/nginx/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 /usr/share/nginx/html;}# proxy the PHP scripts to Apache listening on 127.0.0.1:80##location ~ \.php$ {# proxy_pass http://127.0.0.1;#}# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000##location ~ \.php$ {# root html;# fastcgi_pass 127.0.0.1:9000;# fastcgi_index index.php;# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;# include fastcgi_params;#}# deny access to .htaccess files, if Apache's document root# concurs with nginx's one##location ~ /\.ht {# deny all;#}
}[root@node3 ~]#
[root@node3 ~]# vim /usr/share/nginx/html/index.html
[root@node3 ~]# systemctl restart nginx
[root@node3 ~]# vim /usr/share/nginx/html/index.html
[root@node3 ~]# cat /usr/share/nginx/html/index.html
<!DOCTYPE html>
<html>
<head>
<title>Welcome to guan nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to Guanguan nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p><p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p><p><em>Thank you for using nginx.</em></p>
</body>
</html>
[root@node3 ~]#
案列
启动一个新的虚拟主机
1、编辑配置文件
[root@node3 ~]# vim /etc/nginx/conf.d/guan.conf
[root@node3 ~]# cat /etc/nginx/conf.d/guan.conf
server {listen 80;server_name guan.com;location / {root /guan;index index.html;}
}
[root@node3 ~]# mkdir /guan
[root@node3 ~]# echo "welcome to world" > /guan/index.html
[root@node3 ~]# cat /guan/index.html
welcome to world
2、重启服务
[root@node3 ~]# systemctl restart nginx
3、域名解析和访问
[root@node3 ~]# cat /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.200.184 guan.com
[root@node3 ~]# ping guan.com
PING guan.com (192.168.200.184) 56(84) bytes of data.
64 bytes from guan.com (192.168.200.184): icmp_seq=1 ttl=64 time=0.135 ms
64 bytes from guan.com (192.168.200.184): icmp_seq=2 ttl=64 time=0.052 ms
^C
--- guan.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1017ms
rtt min/avg/max/mdev = 0.052/0.093/0.135/0.042 ms
[root@node3 ~]#
4、本机测试
[root@node3 ~]# elinks http://www.guan.com
bash: elinks: 未找到命令...
[root@node3 ~]# yum install -y elinks [root@node3 ~]# elinks http://guan.com
七、nginx 日志log
1、日志配置
日志模块
官方文档地址:http://nginx.org/en/docs/http/ngx_http_log_module.html
日志模块的名称——ngx_http_log_module
相关指令
log_format
简介:nginx 有非常灵活的日志记录模式。每个级别的配置可以有各自独立的访问日志。日志格式通过 log_format 命令定义。
语法:
log_format name [escape=default | josn ] string
# name 表示格式名称
# string 表示定义的格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for"';
[root@node3 ~]# tailf /var/log/nginx/access.log
192.168.200.1 - - [06/Feb/2023:15:04:40 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.184 - - [06/Feb/2023:15:34:00 +0800] "GET / HTTP/1.1" 200 17 "-" "ELinks/0.12pre6 (textmode; Linux; 103x37-2)" "-"
日志格式允许包含的变量
$remote_addr:远程地址,记录客户端IP地址
$remote_user:远程用户,记录客户端用户名称
[$time_local]: 本地时间,服务器自身时间
“$request”: 请求,记录请求的URL和HTTP协议
$status: 状态,记录请求状态
$body_bytes_sent:发送给客户端的字节数,不包括响应头的大小
“$http_referer”: 记录从那个页面链接访问过来的(超链接)
“$http_user_agent”: 记录客户端浏览器相关信息
“$http_x_forwarded_for”: 代理IP
默认值
access_log
error_log
open_log_file_cache
日志的格式和命令
访问日志和错误日志
案例
[root@node3 ~]# ls /var/log/nginx -l
总用量 8
-rw-r--r--. 1 root root 3919 2月 6 17:30 access.log
-rw-r--r--. 1 root root 3668 2月 6 17:30 error.log
[root@node3 ~]# tailf /var/log/nginx/error.log
2023/02/06 15:33:55 [notice] 33647#33647: worker process 33652 exited with code 0
2023/02/06 17:30:02 [error] 34086#34086: *2 open() "/usr/share/nginx/html/123.html" failed (2: No such file or directory), client: 192.168.200.1, server: localhost, request: "GET /123.html HTTP/1.1", host: "192.168.200.184"
2023/02/06 17:32:06 [error] 34086#34086: *4 open() "/usr/share/nginx/html/abc.html" failed (2: No such file or directory), client: 192.168.200.1, server: localhost, request: "GET /abc.html HTTP/1.1", host: "192.168.200.184"
2023/02/06 17:44:49 [error] 34086#34086: *9 open() "/usr/share/nginx/html/index.html" failed (13: Permission denied), client: 192.168.200.1, server: localhost, request: "GET / HTTP/1.1", host: "192.168.200.184"
[root@node3 ~]# tailf /var/log/nginx/access.log
192.168.200.1 - - [06/Feb/2023:15:05:02 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.184 - - [06/Feb/2023:17:36:34 +0800] "GET / HTTP/1.1" 200 17 "-" "ELinks/0.12pre6 (textmode; Linux; 103x37-2)" "-"
192.168.200.1 - - [06/Feb/2023:17:40:02 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.1 - - [06/Feb/2023:17:44:49 +0800] "GET / HTTP/1.1" 403 555 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.1 - - [06/Feb/2023:17:50:01 +0800] "GET / HTTP/1.1" 200 629 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
[root@node3 nginx]# cd /usr/share/nginx/html/
[root@node3 html]# ls
50x.html index.html
[root@node3 html]# ll
总用量 8
-rw-r--r--. 1 root root 497 10月 19 18:48 50x.html
-rw-r--r--. 1 root root 629 2月 6 15:06 index.html
[root@node3 html]# chmod 000 index.html
[root@node3 html]# ll
总用量 8
-rw-r--r--. 1 root root 497 10月 19 18:48 50x.html
----------. 1 root root 629 2月 6 15:06 index.html
案例:优化404页面
1、修改主配置文件
[root@node3 ~]# vim /etc/nginx/conf.d/guan.conf
[root@node3 ~]# systemctl restart nginx
[root@node3 ~]# cat /etc/nginx/conf.d/guan.conf
server {listen 80;server_name guan.com;location / {root /guan;index index.html;
}error_page 404 /404.html;location = /404.html {root /guan;
}
}
[root@node3 ~]#
2、创建错误反馈页面
[root@node3 ~]# cd /guan/
[root@node3 ~]# cat /guan/404.html
<img src="404.jpg" />
[root@node3 guan]# ls
404.html index.html
[root@node3 guan]# rz #上传图片[root@node3 guan]# ls
404.html 404.jpg index.html
[root@node3 guan]#
3、访问不存在的页面
4、查看404日志
[root@node3 guan]# tailf /var/log/nginx/error.log
2023/02/06 19:35:22 [error] 36239#36239: *1 open() "/guan/abc" failed (2: No such file or directory), client: 192.168.200.184, server: guan.com, request: "GET /abc HTTP/1.1", host: "guan.com"
2023/02/06 19:43:16 [error] 36239#36239: *3 open() "/guan/abc" failed (2: No such file or directory), client: 192.168.200.184, server: guan.com, request: "GET /abc HTTP/1.1", host: "guan.com"
2023/02/06 19:43:18 [error] 36239#36239: *3 open() "/guan/abc" failed (2: No such file or directory), client: 192.168.200.184, server: guan.com, request: "GET /abc HTTP/1.1", host: "guan.com"
日志缓存
简介:大量访问到来时,对于每一条日志记录,都将是先打开文件,在写入日志,然后关闭,占用系统的IO 与业务无关。可以使用 open_log_cache来设置
语法:
open_log_file_cache max=1000 inactive=20s min_uses=3 valid=1m;
- max=1000 指的是日志文件的 FD,最大的缓存数量为1000,超了怎么办,下面下面来解决
- min_uses=3 20秒内小于3次访问的 FD,就直接清除掉,结合inactive 20s 的时间
- valid=1m 检查周期为1分钟。
总结:缓存最多 1000个,到了极限,每分钟开始清除掉 20秒内小于3次的文件 FD。
默认:
open_log_file_cache off;
Context
http,service,location
[root@node3 ~]# vim /etc/nginx/conf.d/guan.conf
[root@node3 ~]# cat /etc/nginx/conf.d/guan.conf
server {open_log_file_cache max=1000 inactive=20s min_uses=3 vaild=1m;listen 80;server_name guan.com;location / {root /guan;index index.html;
}error_page 404 /404.html;location = /404.html {root /guan;
}
}
[root@node3 ~]# systemctl restart nginx
Job for nginx.service failed because the control process exited with error code. See "systemctl status nginx.service" and "journalctl -xe" for details.
[root@node3 ~]# vim /etc/nginx/conf.d/guan.conf
[root@node3 ~]# systemctl restart nginx
[root@node3 guan]# tailf /var/log/nginx/error.log
2023/02/06 20:05:02 [emerg] 38948#38948: invalid "open_log_file_cache" parameter "vaild=1m" in /etc/nginx/conf.d/guan.conf:2
2023/02/06 20:07:03 [notice] 38992#38992: using the "epoll" event method
2023/02/06 20:07:03 [notice] 38992#38992: nginx/1.22.1
2023/02/06 20:07:03 [notice] 38992#38992: built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC)
2023/02/06 20:07:03 [notice] 38992#38992: OS: Linux 5.4.230-1.el7.elrepo.x86_64
2023/02/06 20:07:03 [notice] 38992#38992: getrlimit(RLIMIT_NOFILE): 1024:4096
2023/02/06 20:07:03 [notice] 38994#38994: start worker processes
2023/02/06 20:07:03 [notice] 38994#38994: start worker process 38995
2、日志轮转/切割
前言
nginx 安装,会默认启动日志轮转
[root@node3 ~]# rpm -ql nginx |grep log
/etc/logrotate.d/nginx
/var/log/nginx
[root@node3 ~]# cat /etc/logrotate.d/nginx
/var/log/nginx/*.log {daily # 天missingok # 丢失不提示rotate 52 # 52份compress # 压缩delaycompress # 延时压缩notifempty # 空文件不轮转create 640 nginx admsharedscriptspostrotateif [ -f /var/run/nginx.pid ]; thenkill -USR1 `cat /var/run/nginx.pid`fiendscript
}
[root@node3 ~]#
[root@node3 ~]# cd /etc/logrotate.d/
[root@node3 logrotate.d]# ls
bootlog cups libvirtd nginx psacct samba wpa_supplicant zabbix-server
ceph httpd libvirtd.qemu numad rh-nginx116-nginx syslog yum
chrony iscsiuiolog mysql ppp rh-php72-php-fpm vsftpd zabbix-proxy
[root@node3 logrotate.d]#
3、日志分析
- 日志格式
- 日志条码
- 常用字段
$remote_addr $1 远程客户端地址
$time_local $4 本机时间
$request $7 请求URL
$status $9 状态码
$body_bytes_sent $10 请求体积
案例样本
guan.org.log
[root@node3 ~]# cat guan.org.log
192.168.200.1 - - [06/Feb/2023:15:03:29 +0800] "GET / HTTP/1.1" 200 615 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.1 - - [06/Feb/2023:15:04:37 +0800] "GET / HTTP/1.1" 200 620 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.1 - - [06/Feb/2023:15:04:38 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.1 - - [06/Feb/2023:15:04:38 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.1 - - [06/Feb/2023:15:04:39 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.1 - - [06/Feb/2023:15:04:39 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.1 - - [06/Feb/2023:15:04:39 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.1 - - [06/Feb/2023:15:04:39 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.1 - - [06/Feb/2023:15:04:40 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.1 - - [06/Feb/2023:15:04:40 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.1 - - [06/Feb/2023:15:04:40 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.1 - - [06/Feb/2023:15:04:56 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.1 - - [06/Feb/2023:15:04:56 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.1 - - [06/Feb/2023:15:04:57 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.1 - - [06/Feb/2023:15:04:57 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.1 - - [06/Feb/2023:15:04:57 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.1 - - [06/Feb/2023:15:05:02 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.1 - - [06/Feb/2023:15:06:20 +0800] "GET / HTTP/1.1" 200 629 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.184 - - [06/Feb/2023:15:32:31 +0800] "GET / HTTP/1.1" 200 629 "-" "ELinks/0.12pre6 (textmode; Linux; 103x37-2)" "-"
192.168.200.184 - - [06/Feb/2023:15:34:00 +0800] "GET / HTTP/1.1" 200 17 "-" "ELinks/0.12pre6 (textmode; Linux; 103x37-2)" "-"
192.168.200.1 - - [06/Feb/2023:17:30:02 +0800] "GET /123.html HTTP/1.1" 404 555 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.1 - - [06/Feb/2023:17:32:06 +0800] "GET /abc.html HTTP/1.1" 404 555 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.184 - - [06/Feb/2023:17:36:34 +0800] "GET / HTTP/1.1" 200 17 "-" "ELinks/0.12pre6 (textmode; Linux; 103x37-2)" "-"
192.168.200.1 - - [06/Feb/2023:17:40:02 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.1 - - [06/Feb/2023:17:44:49 +0800] "GET / HTTP/1.1" 403 555 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.1 - - [06/Feb/2023:17:50:01 +0800] "GET / HTTP/1.1" 200 629 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-"
192.168.200.184 - - [06/Feb/2023:19:35:14 +0800] "GET / HTTP/1.1" 200 17 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0" "-"
192.168.200.184 - - [06/Feb/2023:19:35:14 +0800] "GET /favicon.ico HTTP/1.1" 404 24 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0" "-"
192.168.200.184 - - [06/Feb/2023:19:35:22 +0800] "GET /abc HTTP/1.1" 404 24 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0" "-"
192.168.200.184 - - [06/Feb/2023:19:35:23 +0800] "GET /404.jpg HTTP/1.1" 200 52881 "http://guan.com/abc" "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0" "-"
192.168.200.184 - - [06/Feb/2023:19:40:01 +0800] "GET / HTTP/1.1" 200 17 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0" "-"
192.168.200.184 - - [06/Feb/2023:19:43:16 +0800] "GET /abc HTTP/1.1" 404 24 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0" "-"
192.168.200.184 - - [06/Feb/2023:19:43:17 +0800] "GET /404.jpg HTTP/1.1" 304 0 "http://guan.com/abc" "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0" "-"
192.168.200.184 - - [06/Feb/2023:19:43:18 +0800] "GET /abc HTTP/1.1" 404 24 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0" "-"
192.168.200.184 - - [06/Feb/2023:19:43:18 +0800] "GET /404.jpg HTTP/1.1" 304 0 "http://guan.com/abc" "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0" "-"
[root@node3 ~]#
1、统计 2023年2月6日的 PV 量
[root@node3 ~]# grep '06/Feb/2023' guan.org.log | wc -l
35
15点到16点
[root@node3 ~]# grep '06/Feb/2023:15' guan.org.log | wc -l
20
15点到20点之间
[root@node3 ~]# awk '$4>="[06/Feb/2023:15:00:00]" && $4<="[06/Feb/2023:20:00:00]" {print $0}' guan.org.log | wc -l
35
2、统计 2023年2月6日 一天内访问最多的10个IP(ip top10)
[root@node3 ~]# grep '06/Feb/2023' guan.org.log | awk '{ips[$1]++}END{for(i in ips){print i,ips[i]}}' | sort -k2 -m | head -n10
192.168.200.1 23
192.168.200.184 12
3、统计 2023年2月6日 访问大于20次的
IP
[root@node3 ~]# grep '06/Feb/2023' guan.org.log | awk '{ips[$1]++}END{for(i in ips){if(ips[i]>20){print i,ips[i]} }}'
192.168.200.1 23
4、统计 2023年2月6日 访问最多的10个页面($request 10)
[root@node3 ~]# grep '06/Feb/2023' guan.org.log | awk '{url[$7]++}END{for(i in url){print url[i],i }}' | sort -k1 -rn | head -10
26 /
3 /abc
3 /404.jpg
1 /favicon.ico
1 /abc.html
1 /123.html
[root@node3 ~]#
5、统计 2023年2月6日 每个URL访问内容总大小($body_bytes_sent)
[root@node3 ~]# grep '06/Feb/2023' guan.org.log | awk '{urls[$7]++;size[$7]+=$10}END{for(i in urls){print urls[i],size[i],i }}' | sort -k1 -rn | head -10
26 3745 /
3 72 /abc
3 52881 /404.jpg
1 555 /abc.html
1 555 /123.html
1 24 /favicon.ico
[root@node3 ~]#
6、统计 2023年2月6日 每个IP访问状态码数量($status)
[root@node3 ~]# awk '{status[$9]++}END{for(i in status){print i,status[i]}}' guan.org.log |sort -k2 -rn304 18
200 10
404 6
403 1
[root@node3 ~]#
[root@node3 ~]# grep '06/Feb/2023' guan.org.log | awk '{ip_code[$1" "$9]++}END{for(i in ip_code){print i,ip_code[i]}} '| sort -k3 -rn
192.168.200.1 304 16
192.168.200.184 200 6
192.168.200.184 404 4
192.168.200.1 200 4
192.168.200.184 304 2
192.168.200.1 404 2
192.168.200.1 403 1
[root@node3 ~]#
7、统计 2023年2月6日 每个IP访问状态码为404及出现的次数($status)
[root@node3 ~]# grep '06/Feb/2023' guan.org.log | awk '{ if($9=="404"){ip_code[$1" "$9]++}}END{for(i in ip_code){print i,ip_code[i]}} '| sort -k3 -rn
192.168.200.184 404 4
192.168.200.1 404 2
[root@node3 ~]#
8、统计前一分钟的PV量
[root@node3 ~]# date
2023年 02月 06日 星期一 23:14:01 CST
[root@node3 ~]# date -d '-1 minute'
2023年 02月 06日 星期一 23:13:18 CST[root@node3 ~]# date -d '-1 minute' +%Y:%H:%M
2023:23:15
[root@node3 ~]# guan_date=`date -d '-1 minute' +%Y:%H:%M`;echo $guan_date
2023:23:16[root@node3 ~]# guan_date=`date -d '-1 minute' +%Y:%H:%M`;awk -v guan_date=$guan_date '$0 ~ guan_date{i++} END{print i}' /var/log/nginx/access.log[root@node3 ~]# guan_date=`date -d '-1 minute' +%Y:%H:%M`;awk -v guan_date=$guan_date '$0 ~ guan_date{i++} END{print i}' /var/log/nginx/access.log
65
[root@node3 ~]#
9、统计2023年2月6日 15:00~20:00,每个 IP 出现404状态码的数量
[root@node3 ~]# awk '$4>"[06/Feb/2023:15:00:00]" && $4<"[06/Feb/2023:20:00:00]"{if($9=="404"){ip_code[$1" "$9]++}} END{for(i in ip_code){print i,ip_code[i]}}' guan.org.log
192.168.200.184 404 4
192.168.200.1 404 2
10、统计2023年2月6日 各种状态码的数量
[root@node3 ~]# grep '06/Feb/2023' guan.org.log | awk '{code[$9]++} END{for(i in code){print i,code[i]}}' |sort -k2 -rn
304 18
200 10
404 6
403 1
[root@node3 ~]#
八、nginx web 模块
1、连接状态
stub_status_module
目的:
查询模块是否安装
[root@node3 ~]# nginx -V 2>&1 | grep stub_status
--with-http_stub_status_module
启动状态模块
- 访问默认站点的状态模块(注意:错误验证)
未启用
- 配置状态模块
启用该模块
[root@node3 ~]# vim /etc/nginx/conf.d/default.conf
[root@node3 ~]# cat /etc/nginx/conf.d/default.conf
server {location /nginx_status{stub_status;allow all; }
}
- 重启服务再次访问
[root@node3 ~]# systemctl restart nginx
观察连接数和请求数
Active connections: 1 # 当前活动的连接数
server accepts handled requests # 服务器接受处理请求1 1 1 # 1 总连接数connection(TCP)# 1 成功连接数connection(TCP)# 总共处理的请求数request(HTTP)
Reading: 0 Writing: 1 Waiting: 0# Reading: 0 读取客户端Header的信息数 请求头
# Writing: 1 返回给客户端的header的信息 响应头
# Waiting: 0 等待的请求数,开启了keepalive
关于链接的问题
- 什么是链接
1.OSI 数据封装与解封
2.TCP 封装结构
3.TCP 三次握手
4.TCP 四次挥手/四次断开
5.TCP 机制
6.TCP 流程/拥塞管理
- 什么是请求
即一次 HTTP 请求 - keepalived
长连接设置
Httpd 守护进程,一般提供了keep-alive timeout 时间设置参数。比如nginx的 keepalive_timeout,和Apache的AliveTimeout。这个 keepalive_timeout时间值意味着:一个http产生的 tcp 连接在传送完最后一个响应后,还需要 hold 住 keepalive_timeout 后,才开始关闭这个连接。当httpd守护进程发送一个响应后,理应马上主动关闭相应的tcp连接,设置 keepalive_timeout 后,httpd守护进程会想说:“在等等吧,看看浏览器还有没有请求过来”,这一等,便是 keepalive_timeout 时间。如果守护进程在这个等待的时间里,一直没有收到浏览器发过来 http 请求,则关闭这个 http 连接。
关闭长连接会如何
再次刷新状态并观察
2、随机主页
微更新
random_index_module
目的:将主页设置成随机页面,是一种微调更新机制
启动随机主页
- 创建主页目录
mkdir /app
- 创建多个主页
touch /app/{blue.html,green.html,red.html,.yellow.html}
[root@node3 app]#touch /app/{blue.html,green.html,red.html,.yellow.html}
[root@node3 app]# ls
blue.html green.html red.html
[root@node3 app]# ls -a
. .. blue.html green.html red.html .yellow.html
[root@node3 app]#
[root@node3 app]# vim red.html
[root@node3 app]# vim red.html
[root@node3 app]# vim blue.html
[root@node3 app]# vim green.html
[root@node3 app]# vim .yellow.html
[root@node3 app]# cat .yellow.html
<html>
<head>
<title>yellow color</title>
</head>
<body style="background-color:yellow">
<h1>yellow color!</h1>
</body>
</html>[root@node3 app]# cat green.html
<html>
<head>
<title>green color</title>
</head>
<body style="background-color:green">
<h1>green color!</h1>
</body>
</html>
[root@node3 app]# cat blue.html
<html>
<head>
<title>blue color</title>
</head>
<body style="background-color:blue">
<h1>blue color!</h1>
</body>
</html>[root@node3 app]# cat blue.html
<html>
<head>
<title>blue color</title>
</head>
<body style="background-color:blue">
<h1>blue color!</h1>
</body>
</html>[root@node3 app]#
- 启动随机主页
默认的
location / {root /usr/share/nginx/html;index index.html index.htm;}
将默认的注释掉,修改之后如下
location / {# root /usr/share/nginx/html;# index index.html index.htm;root /app;random_index on;}
重启服务器
[root@node3 app]# systemctl restart nginx
刷新主页观察变化
3、替换模块
sub_module
目的:网页内容替换
如果我们用模板生成网站的时候,因为疏漏或者别的原因造成代码不如意,但是此时因为文件数量巨大,不方便全部重新生成,那么这个时候我们就可以用此模块来暂时实现纠错。另一方面,我们也可以利用这个实现服务器端文字过滤的效果。
- 启动替换1
[root@node3 app]# cat /etc/nginx/conf.d/default.conf
server {# 替换模块 将nginx 替换成 Guan# 单次替换 关闭sub_filter nginx "Guan"; sub_filter_once off;location /nginx_status{stub_status;allow all; }listen 80;server_name localhost;#access_log /var/log/nginx/host.access.log main;location / {root /usr/share/nginx/html;index index.html index.htm;# root /app;# random_index on;}#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 /usr/share/nginx/html;}# proxy the PHP scripts to Apache listening on 127.0.0.1:80##location ~ \.php$ {# proxy_pass http://127.0.0.1;#}# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000##location ~ \.php$ {# root html;# fastcgi_pass 127.0.0.1:9000;# fastcgi_index index.php;# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;# include fastcgi_params;#}# deny access to .htaccess files, if Apache's document root# concurs with nginx's one##location ~ /\.ht {# deny all;#}
}[root@node3 app]#
[root@node3 app]# systemctl restart nginx
4、文件读取
模块
ngx_http_core_module
原理介绍:
- sendfile:
未使用 sendfile() 的传统网络传输过程:
硬盘>>kernel buffer>>user buffer>>kernel socket buffer>>协议栈
使用 sendfile() 来进行网络传输过程:
硬盘>>kernel buffer(快速拷贝到kernel socket buffer )>>协议栈
sendfile() 不但能减少切换次数而且还能减少拷贝次数
[root@node3 app]# cat /etc/nginx/nginx.confuser nginx;
worker_processes auto;error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;events {worker_connections 1024;
}http {include /etc/nginx/mime.types;default_type application/octet-stream;log_format main '$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for"';access_log /var/log/nginx/access.log main;sendfile on;#tcp_nopush on;keepalive_timeout 65;#gzip on;include /etc/nginx/conf.d/*.conf;
}
[root@node3 app]#
- tcp_nopush
sendfile on;
tcp_nopush on;
未使用 tcp_nopush()网络资源浪费
应程序每产生一次操作就会发送一个包,而典型情况下一个包会拥有一个字节的数据以及40个字节长的包头,于是产生 4000% 的过载,很轻易地就能令网络发生拥塞,同时也浪费资源
使用 tcp_nopush()网络传输效率提升
当包累计到一定大小后再发送
- tcp_nodealy
开启或关闭nginx 使用TCP_NODELAY 选项的功能,这个选项仅在将连接转变为长连接的时候才被启用。
TCP_NODELAY 是禁用Nagle 算法,及数据包立即发送出去。由于 Nagle 和 DelayedACK 的原因,数据包的确认信息需要积攒到两个时才发送,长连接情况下,奇数包会造成延时40ms,所以tcp_dodelay 会将ack立刻发出去。如果不在长连接时,可以关闭次模块,因为ack会被立刻发出去。
[root@node3 app]# cat /etc/nginx/nginx.confsendfile on;tcp_nopush on;tcp_nodelay on;
[root@node3 app]# systemctl restart nginx
5、文件压缩
原理介绍: 启用该模块,使文件传输前进压缩,提升传输效率。
模块
ngx_http_gzip_module
语法:
Syntax: gzip on | off;
Default: gzip off;
Context: http,server,location,if in locationSyntax: gzip_comp_level level;
Default: gzip_comp_level 1;#(1~9)
Context: http,server,locationSyntax: gzip_http_version 1.0 | 1.1;
Default: gzip_http_version 1.1;
Context: http,server,location
启用模块
- 观察未压缩传输
1.拷贝图片到网站主目录
[root@node3 ~]# cd /usr/share/nginx/html
[root@node3 html]# ls
50x.html index.html
[root@node3 html]# vim test.html
[root@node3 html]# ls
50x.html index.html test.html
[root@node3 html]# ll -h
总用量 376K
-rw-r--r--. 1 root root 497 10月 19 18:48 50x.html
-rwxr-xr-x. 1 root root 629 2月 6 15:06 index.html
-rw-r--r--. 1 root root 366K 2月 7 20:42 test.html
[root@node3 html]#
2.拷贝tar包到网站主目录
3.拷贝文件到文件主目录
4.通过浏览器下载文件并观察下载后的大小
- 启用压缩功能
[root@node3 html]# vim /etc/nginx/nginx.conf
http {gzip on;gzip_http_version 1.1;gzip_comp_level 2;gzip_types text/plain application/javascript application/x-javascript text/css application/xml text
/javascript application/x-httpd-php image/jpeg image/png;gzip_static on;
}
重启服务器
[root@node3 html]# systemctl restart nginx
- 观察压缩后文件传输的大小
注意缓存
压缩包和图片类对象本身已经自带压缩功能,所以压缩比例较小。文本类对象在压缩实验中,压缩比例体现优越。在通过浏览器下载文件并观察下载后的文件的大小。
6、页面缓存
模块
ngx_http_headers_module
expires 起到控制页面缓存的作用,合理的配置 expires可以减少很多服务器的请求,要配置expires可以在http段中、server段中、location段中加入。
nginx(expires 缓存减轻服务器压力)
语法:
Syntax: expires[modified] time;expires epoch | max | off;
Default: expires off;
Context: http,server,location,if in location
原理介绍:无缓存,每次访问服务器都是全文传输,开启缓存可以加速浏览网站。
启用缓存:
- 观察浏览器缓存
1.开启浏览器缓存,浏览页面。(默认)
第一次返回状态码200,页面对象全文传输
第二次返回状态码304,页面对象部分传输
2.禁用缓存,浏览页面
3.解析缓存原理
- 理解nginx服务器缓存
4.开启服务器缓存模块
[root@node3 html]# vim /etc/nginx/conf.d/default.conflocation / {expires 24h;root /usr/share/nginx/html;index index.html index.htm;# root /app;# random_index on;}root@node3 html]systemctl restart nginx
5.再次浏览页面,观察响应头中出现服务器回复的缓存
24h = 86400s
12h=43200s
6.理解nginx服务器启动缓存时间,加速浏览
7、防盗链
模块:
在这里插入代码片
语法:
日志原理介绍
启动防盗链
- 搭建一个a.com网站
在主页插入图片
[root@node3 ~]# cd /etc/nginx/conf.d
[root@node3 conf.d]# ls
default.conf guan.conf
[root@node3 conf.d]# vim a.com.conf
[root@node3 conf.d]# cat a.com.conf
server {listen 80;server_name a.com;lcation / {root /a.com;index index.html;
}
}
[root@node3 conf.d]# ls
a.com.conf default.conf guan.conf
[root@node3 conf.d]# mkdir /a.com
[root@node3 conf.d]# vim /a.com/index.html
[root@node3 conf.d]# cd /a.com/
[root@node3 a.com]# ls
index.html
[root@node3 a.com]# cat /a.com/index.html
<img src='test.jpg' />
[root@node3 a.com]# rz
[root@node3 a.com]# ls
index.html test.jpg
[root@node3 a.com]#
[root@node3 a.com]# ll #查看是否有读取照片的权限
总用量 348
-rw-r--r--. 1 root root 23 2月 7 23:56 index.html
-rw-r--r--. 1 root root 350627 12月 18 14:12 test.jpg
注意:要将test.jpg拷贝到网站主目录
- 搭建一个b.com网站
在主页中盗链a网站的图片
[root@node3 a.com]# ls /etc/nginx/conf.d
a.com.conf default.conf guan.conf
[root@node3 a.com]# vim /etc/nginx/conf.d/b.com
[root@node3 a.com]# cat /etc/nginx/conf.d/b.com
server {listen 80;server_name b.com;location / {root /b.com;index index.html;
}
}[root@node3 a.com]# ls /etc/nginx/conf.d
a.com.conf b.com.conf default.conf guan.conf
[root@node3 a.com]#
[root@node3 b.com]# vim index.html
[root@node3 b.com]# cat index.html
<img src="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0515%2Fce5834a3j00rbxcc20025c000hs00voc.jpg&thumbnail=660x2147483647&quality=80&type=jpg" />
[root@node3 b.com]# ls
index.html
<img src=“http://a网站的域名或者(图片)地址” />
注意:网站主目录中没有图片
- 访问两个网站页面,都能正常显示图片
a.com
b.com
[root@node3 b.com]# cat index.html
<img src="http://a.com/test.jpg" />
[root@node3 b.com]# systemctl restart nginx
- 注意a.com网站的日志
[root@node3 b.com]# vim /etc/nginx/conf.d/default.conf
# /var/log/nginx/b.com.access.log main;
[root@node3 a.com]# cd /etc/nginx/conf.d/
[root@node3 conf.d]# ls
a.com.conf b.com.conf default.conf guan.conf
[root@node3 conf.d]# vim a.com.conf [root@node3 conf.d]# cat a.com.conf
server {access_log /var/log/nginx/a.com.access.log main;listen 80;server_name a.com;location / {root /a.com;index index.html;
}
}
[root@node3 conf.d]#
进行 a.com和b.com的日志分离
- 注意b.com网站的日志
[root@node3 conf.d]# vim b.com.conf
[root@node3 conf.d]# cat b.com.conf
server {access_log /var/log/nginx/b.com.access.log main;listen 80;server_name b.com;location / {root /b.com;index index.html;
}
}
修改配置文件后需要重启服务
[root@node3 conf.d]# systemctl restart nginx
a.com和b.com的日志分离后的效果
[root@node3 conf.d]# ls /var/log/nginx
access.log access.log-20230207 a.com.access.log b.com.access.log error.log error.log-20230207
[root@node3 conf.d]#
启动a.com防盗链功能
生产环境:
location ~*\.(gif|ipg|png|bmp)$ {root /a.comvalid_referers none blocked *.a.com server_name ~\.google\. ~\.baidu\. b.com 192.168.200.* a.com;if ($invalid_referer){return 403;#rewrite .*http://a.com/test.jpg;
}
[root@node3 conf.d]# cat a.com.conf
server {access_log /var/log/nginx/a.com.access.log main;listen 80;server_name a.com;location / {root /a.com;index index.html;valid_referers none blocked *.a.com; #防盗链if ($invalid_referer){return 403;
}
}
}
再次访问b.com网站,防盗链失败
如果希望网站能够使用(盗链)资源
[root@node3 conf.d]# cat a.com.conf
server {access_log /var/log/nginx/a.com.access.log main;listen 80;server_name a.com;location / {root /a.com;index index.html;valid_referers none blocked *.a.com server_name ~\.google\. ~\.baidu\. b.com 192.168.200.* a.com;# server_name后跟白名单if ($invalid_referer){return 403;
}
}
}
[root@node3 conf.d]# systemctl restart nginx
[root@node3 conf.d]#
- 再次盗链,合法盗链成功
九、nginx 访问限制
ngx_http_limit_req_module
目的:启动请求频率限制
0 测试未限制情况下的访问
[root@node3 conf.d]# yum install -y httpd-tools
[root@node3 conf.d]# ab -n 100 -c 10 http://a.com/
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 a.com (be patient).....doneServer Software: nginx/1.22.1
Server Hostname: a.com
Server Port: 80Document Path: /
Document Length: 23 bytesConcurrency Level: 10
Time taken for tests: 0.021 seconds
Complete requests: 100
Failed requests: 0
Write errors: 0
Total transferred: 25400 bytes
HTML transferred: 2300 bytes
Requests per second: 4667.01 [#/sec] (mean)
Time per request: 2.143 [ms] (mean)
Time per request: 0.214 [ms] (mean, across all concurrent requests)
Transfer rate: 1157.64 [Kbytes/sec] receivedConnection Times (ms)min mean[+/-sd] median max
Connect: 0 0 0.3 0 1
Processing: 0 1 0.6 1 6
Waiting: 0 1 0.5 1 5
Total: 1 2 0.7 1 7
WARNING: The median and mean for the total time are not within a normal deviationThese results are probably not that reliable.Percentage of the requests served within a certain time (ms)50% 166% 275% 280% 290% 295% 298% 299% 7100% 7 (longest request)
[root@node3 conf.d]#
1 启动限制
[root@node3 conf.d]# vim /etc/nginx/nginx.conf
http {limit_req_zone $binary_remote_addr zone=req_zone:10m rate=1r/s;
}
[root@node3 conf.d]# ls
a.com.conf b.com.conf default.conf guan.conf
[root@node3 conf.d]# vim a.com.conf
[root@node3 conf.d]# cat a.com.conf
server {access_log /var/log/nginx/a.com.access.log main;listen 80;server_name a.com;location / {limit_req zone=req_zone; # 引用 限制策略的名称root /a.com;index index.html;valid_referers none blocked *.a.com server_name ~\.google\. ~\.baidu\. b.com 192.168.200.* a.com;if ($invalid_referer){return 403;
}
}
}
[root@node3 conf.d]#
2 重启服务并测试
[root@node3 conf.d]# systemctl restart nginx
[root@node3 conf.d]# ab -n 100 -c 10 http://a.com/
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 a.com (be patient).....doneServer Software: nginx/1.22.1
Server Hostname: a.com
Server Port: 80Document Path: /
Document Length: 23 bytesConcurrency Level: 10
Time taken for tests: 0.018 seconds
Complete requests: 100
Failed requests: 99(Connect: 0, Receive: 0, Length: 99, Exceptions: 0)
Write errors: 0
Non-2xx responses: 99
Total transferred: 36785 bytes
HTML transferred: 19526 bytes
Requests per second: 5442.18 [#/sec] (mean)
Time per request: 1.837 [ms] (mean)
Time per request: 0.184 [ms] (mean, across all concurrent requests)
Transfer rate: 1954.99 [Kbytes/sec] receivedConnection Times (ms)min mean[+/-sd] median max
Connect: 0 0 0.1 0 1
Processing: 0 1 1.0 0 10
Waiting: 0 0 0.9 0 10
Total: 0 1 1.0 1 10Percentage of the requests served within a certain time (ms)50% 166% 175% 180% 190% 195% 198% 299% 10100% 10 (longest request)
[root@node3 conf.d]#
3 观察错误日志
[root@node3 conf.d]# cat /var/log/nginx/error.log
...
2023/02/08 02:00:59 [error] 282701#282701: *99 limiting requests, excess: 0.984 by zone "req_zone", client: 192.168.200.184, server: a.com, request: "GET / HTTP/1.0", host: "a.com"
2023/02/08 02:00:59 [error] 282701#282701: *100 limiting requests, excess: 0.983 by zone "req_zone", client: 192.168.200.184, server: a.com, request: "GET / HTTP/1.0", host: "a.com"
ngx_http_limit_conn_module
目的:通过IP地址,限制连接(TCP),但是实验环境无法测试
启动连接频率限制
1.启动连接频率限制
2.测试
3.效果不明显
4.了解不同的网站压力测试工具
十、nginx 访问控制
基于主机(ip)
module:ngx_http_access_module
Directives:
allow(允许某些主机)
deny(拒绝某些主机)
Syntax:
Syntax: allow address | CIDR | unix: | all
Context: http,server,location,limit_except
1.限制访问主机
[root@node3 conf.d]# vim /etc/nginx/conf.d/a.com.conf
server {allow 192.168.200.181;deny all; ...
}
[root@node3 conf.d]# systemctl restart nginx
2.测试
192.168.200.181 这台服务器访问成功
192.168.200.184 这台服务器访问失败
基于用户(username&password)
module:ngx_http_auth_basic_module
语法:
Syntax:auth_basic string | off;
Context: http,server,location,limit_execpt
Syntax:auth_basic_user_file file;
Context: http,server,location,limit_execpt
启用控制
- 建立认证文件
[root@node3 conf.d]# yum install -y httpd-tools
[root@node3 conf.d]# htpasswd -cm /etc/nginx/conf.d/passwd user10
New password:
Re-type new password:
Adding password for user user10
[root@node3 conf.d]# cat /etc/nginx/conf.d/passwd
user10:$apr1$FzzIdFAI$VBdBrYVR1CUUAA3/lMBLj1
[root@node3 conf.d]# htpasswd -m /etc/nginx/conf.d/passwd user20
New password:
Re-type new password:
Adding password for user user20
[root@node3 conf.d]# cat /etc/nginx/conf.d/passwd
user10:$apr1$FzzIdFAI$VBdBrYVR1CUUAA3/lMBLj1
user20:$apr1$IKnRjXQK$E6Dpv69RfGcYnya/rFZ0C0
[root@node3 conf.d]#
- 启动认证
[root@node3 conf.d]# vim /etc/nginx/conf.d/a.com.conf
server {auth_basic "welcom to big world!";auth_basic_user_file /etc/nginx/conf.d/passwd;...
}
[root@node3 conf.d]# cat /etc/nginx/conf.d/a.com.conf
server {auth_basic "welcom to big world!";auth_basic_user_file /etc/nginx/conf.d/passwd;allow 192.168.200.181; allow 192.168.200.184;deny all; access_log /var/log/nginx/a.com.access.log main;listen 80;server_name a.com;location / {#limit_req zone=req_zone; root /a.com;index index.html;valid_referers none blocked *.a.com server_name ~\.google\. ~\.baidu\. b.com 192.168.200.* a.com;if ($invalid_referer){return 403;
}
}
}
[root@node3 conf.d]#
- 重启并验证
【NGINX入门指北】 基础篇相关推荐
- Sky Hackthon比赛指北-基础篇
无图预警,多字预警. 阅读时请保持清醒,有利于发现谬误. 关于Sky Hackthon Sky Hackthon 比赛是由 Nvidia 中国开发者社区举办的,面向国内高校学生的关于算法模型应用比赛, ...
- 【Linux入门指北】第一篇 初识Linux
目录 前言 一.Linux操作系统的发展历史 1.Linux操作系统的诞生 2.Linux操作系统的发展 1.自由软件基金会(FSF) 2.GPL协议 3.GUN工程 二.Linux的不同发行版本 1 ...
- Python 简单入门指北(二)
Python 简单入门指北(二) 2 函数 2.1 函数是一等公民 一等公民指的是 Python 的函数能够动态创建,能赋值给别的变量,能作为参传给函数,也能作为函数的返回值.总而言之,函数和普通变量 ...
- 计算机学习入门指北——计科软工网络信安侧重图析、解读专业术语、岗位分类、未来规划
申明:本博文偏技术向,主观性较强,其中部分理解必有偏差和误解,望指出改正! 计算机学习入门指北: 作为刚入学的计算机系学生,面对一片专业术语十分蒙.区块链?大数据?开源?数据库?嵌入式开发?前端后端? ...
- 萌妹子Python入门指北(二)
原文来自 (ixindoo.com)[http://ixindoo.com/articles/662] 只写了第一篇就好久没更新了,为啥?因为妹子学编程的意愿不强了,我也不能逼迫她去学.不过后来收到部 ...
- Python 简单入门指北(试读版)
本文是我小专栏中 Python 简单入门指北 一文的前半部分,如果你能坚持读完并且觉得有一定收获,建议阅读原文,只需一杯咖啡钱就可以阅读更精彩的部分,也可以订阅小专栏或者加入我的知识星球,价格都是 6 ...
- Blockly开发入门指北
Blockly开发入门指北 [腾讯文档]Blockly开发入门指北 https://docs.qq.com/doc/DRWRDUU5kR2lhaGNN 写这篇文章的目的 最近公司的项目用到了Block ...
- Flutter 入门指北(Part 9)之弹窗和提示(SnackBar、BottomSheet、Dialog)
该文已授权公众号 「码个蛋」,转载请指明出处 前面的小节把常用的一些部件都介绍了,这节介绍下 Flutter 中的一些操作提示.Flutter 中的操作提示主要有这么几种 SnackBar.Botto ...
- 新司机的黑裙战斗机 篇四:新司机的黑群晖指北—软件篇(下)
原文网址:https://post.smzdm.com/p/awxl3d44/ 各位剁友好,我是身在长沙的一只小剁,因为ID的缘故长沙剁友赐雅号--姐夫 本文是我的首个系列<新司机的黑裙战斗机& ...
最新文章
- 解决Mac下npm权限问题
- python 数组数据类型
- 用户强烈反对产品改动,如何应对?
- Inotify+Rsync实现linux文件实时同步
- C#的Timer解析(转)
- 关于 VDD VSS VCC VEE VPP
- python随机数据随概率分布_概率分布及其Python实现
- js怎么获取扫码枪条码_生产扫码计件解决方案
- php7.3 mysql gd支持_配置PHP对gd库的支持
- 程序开源与不开源区别_什么是开源程序办公室? 为什么需要一个?
- android 微信 demo,android微信分享demo
- 【LeetCode】面试题 03. 数组中重复的数字
- SQL Server自动化运维系列——监控磁盘剩余空间及SQL Server错误日志(Power Shell)...
- Ora-12505 故障
- matlab实现S函数的五种方式
- 做正确的事(效果)比正确的做事(效率)更重要
- 专访贤华老师:阐释护肤真谛
- 信用的“刚柔并进”大家信夫的普惠信用
- python实现PDF压缩
- Linux基本操作1
热门文章
- Tiny4412汇编流水灯代码,Tiny4412裸机LED操作[1]
- 安卓3:Android文件目录详解-manifest文件夹和java文件夹
- 商汤科技2018年校招
- 2020前端工作总结
- 【转】 很美的句子,句句掉泪,不知道原创是谁,感谢
- 一个永久免费的图片鉴黄api接口
- 在数据库EMIS1中;把日志文件初始大小修改为10MB,增长量为每次增长5MB,最大大小保持不变。
- ubuntu下网页快捷方式,chrome网页添加到桌面
- 一个可恶的javascript病毒/木马解码之后的代码
- Android_AsyncTaskDemo之QQ记步数(画圆形图片知识)