参考老男孩培训机构教学视频编写
鸣谢:https://www.zutuanxue.com 白树明
一、Nginx概念
1.1 Nginx是什么
Nginx(“engine x”)是一款是由俄罗斯的程序设计师Igor Sysoev所开发高性能的 Web和 反向代理服务器,也是一个 IMAP/POP3/SMTP 代理服务器。和apache一样,都是web服务器软件,因为其性能优异,所以被广大运维喜欢。又因为nginx是一个轻量级的web服务器,相比apache来说资源消耗更低。
1.2 Nginx可以做什么
web服务器
反向代理
负载均衡
动静分离
1.3 下载Nginx源码安装包
网站地址为:http://nginx.org/,可下载源码下载文件
中文指引文档链接:https://www.nginx.cn/doc/index.html,有详细的基本模块介绍和配置实例
1.4 Nginx的源码包安装
1.4.1 下载Nginx源码包
[root@nginx1 src]#wget http://nginx.org/download/nginx-1.19.3.tar.gz -P /usr/src
[root@nginx1 src]# ls
debug kernels nginx-1.19.3.tar.gz
[root@nginx1 src]#
-P /usr/src
:指定源码包下载后的存放目录
1.4.2 安装nginx依赖环境
中途小插曲:在打算用yum install gcc时候系统报错,提示:
yum提示Another app is currently holding the yum lock; waiting for it to exit...
,查看进程发现已经有一个yum经常在运行中了,只能用下面的命令强制关闭进程
[root@nginx1 src]# rm -f /var/run/yum.pid
正式开始安装依赖环境:
[root@nginx1 src]#yum -y install gcc pcre-devel zlib-devel
- gcc: 源码编译工具
- pcre-devel: nginx url_rewrite 功能提供包
- zlib-devel: nginx 压缩功能提供包
1.4.3 解压源码,并进入解压后的目录
[root@nginx1 src]# tar xzvf nginx-1.19.3.tar.gz
[root@nginx1 src]# ls
debug kernels nginx-1.19.3 nginx-1.19.3.tar.gz
[root@nginx1 src]# cd nginx-1.19.3/
[root@nginx1 nginx-1.19.3]# ls
auto CHANGES CHANGES.ru conf configure contrib html LICENSE man README src
[root@nginx1 nginx-1.19.3]#
1.4.4 配置nginx 源码
[root@nginx1 nginx-1.19.3]# ./configure --prefix=/usr/local/nginx
1.4.5 编译并安装nginx源码
[root@nginx1 nginx-1.19.3]# make j2
[root@nginx1 nginx-1.19.3]# make install
1.4.6 安装完成后进入安装目录查看目录结构
[root@nginx1 local]# cd /usr/local/nginx/
[root@nginx1 nginx]# tree
.
├── conf
│ ├── fastcgi.conf
│ ├── fastcgi.conf.default
│ ├── fastcgi_params
│ ├── fastcgi_params.default
│ ├── koi-utf
│ ├── koi-win
│ ├── mime.types
│ ├── mime.types.default
│ ├── nginx.conf 配置文件
│ ├── nginx.conf.default
│ ├── scgi_params
│ ├── scgi_params.default
│ ├── uwsgi_params
│ ├── uwsgi_params.default
│ └── win-utf
├── html 网页根目录
│ ├── 50x.html
│ └── index.html
├── logs 日志
└── sbin
└── nginx 启动文件
1.4.7 nginx常用命令
- 启动:/usr/local/nginx/sbin/nginx
- 关闭:
killall –s QUIT nginx
/usr/local/nginx/sbin/nginx -s stop
/usr/local/nginx/sbin/nginx -s quit - 查看版本号:/usr/local/nginx/sbin/nginx -v
- 重新热加载nginx配置文件:/usr/local/nginx/sbin/nginx -s reload
- 测试配置文件是否正确可运行:/usr/local/nginx/sbin/nginx -t
- 查看nginx是否正常启动:
[root@nginx1 nginx]# netstat -tunpl | grep nginx
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 7638/nginx: master
[root@nginx1 nginx]#
#可以看到nginx已经正常启动了,监听端口为80
二、nginx配置文件解读
-----------------------------------------------------------------------------------
#全局块
#启动子进程程序默认用户
#user nobody;
#一个主进程和多个工作进程,工作进程是单进程的,且不需要特殊授权即可运行,一般与CPU的核数一致
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
------------------------------------------------------------------------------------
#event块
events {
worker_connections 1024;
}
-------------------------------------------------------------------------------------
#http服务器配置
http {
include mime.types; 设定mime类型,类型由mime.type文件定义
default_type application/octet-stream;
#access日志格式
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
log_format格式变量:
$remote_addr #记录访问网站的客户端地址
$remote_user #远程客户端用户名
$time_local #记录访问时间与时区
$request #用户的http请求起始行信息
$status #http状态码,记录请求返回的状态码,例如:200、301、404等
$body_bytes_sent #服务器发送给客户端的响应body字节数
$http_referer #记录此次请求是从哪个连接访问过来的,可以根据该参数进行防盗链设置。(从哪里跳转过来的)
$http_user_agent #记录客户端访问信息,例如:浏览器、手机客户端等
$http_x_forwarded_for #当前端有代理服务器时,设置web节点记录客户端地址的配置,此参数生效的前提是代理服务器也要进行相关的x_forwarded_for设置
#全局访问日志路径
#access_log logs/access.log main; #main是上方定义的日志格式
#sendfile 指令指定nginx是否调用sendfile行数(Zero copy)来输出文件,对于普通应用,必须为on
sendfile on;
#此选项允许或者禁止使用socket的TCP_CORK的选项,此选项仅在使用sendfile的时候使用
#tcp_nopush on;
#长连接超时时间
#keepalive_timeout 0;
keepalive_timeout 65;
#开启压缩
#gzip on;
#配置虚拟主机
server {
#虚拟主机使用的端口
listen 80;
#虚拟主机域名
server_name localhost;
#虚拟主机支持的字符集
#charset koi8-r;
#虚拟主机的访问日志路径
#access_log logs/host.access.log main;
#定义web根路径
location / {
#根目录路径,相对于安装路径/usr/local/nginx来说
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;
# 错误页的路径,“=”精确匹配URL
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;
# }
#}
}
三、nginx实操
3.1 编写默认网站页面,请求错误返回404错误页,子进程用户为www
1. 修改nginx.conf配置文件
[root@nginx1 conf]# more nginx.conf
user www;
worker_processes 2;
#error_log logs/error.log;
#error_log logs/error.log notice;
error_log logs/error.log info;
pid logs/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 5;
#gzip on;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 404 /404.html;
location = /404.html {
root html;
}
# redirect server error pages to the static page /50x.html
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
2.创建www用户
[root@nginx1 conf]# useradd -s /sbin/nologin -r www
useradd -r www
:表示创建的是系统用户
3.检查nginx.conf配置文件是否正确
[root@nginx1 conf]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@nginx1 conf]#
4.在 /usr/local/nginx/html目录新建 404.html文件
[root@nginx1 html]# echo "the resource is not exist!!! " > 404.html
5.重新加载nginx配置文件
[root@nginx1 html]# /usr/local/nginx/sbin/nginx -s reload
6.用lsof 命令查看nginx程序是否正常运行
[root@nginx1 html]# lsof -i :80
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
nginx 7638 root 6u IPv4 74369 0t0 TCP *:http (LISTEN)
nginx 11734 www 6u IPv4 74369 0t0 TCP *:http (LISTEN)
nginx 11735 www 6u IPv4 74369 0t0 TCP *:http (LISTEN)
[root@nginx1 html]#
7.测试
- 当访问正常url时
- 当访问不存在的url时,返回404错误页
3.2 IP访问控制
只允许特定的10.10.0.0.24段访问,其他重定向至http://www.baidu.com
1. 修改 nginx.conf配置文件
[root@nginx1 conf]# cat nginx.conf
user www;
worker_processes 2;
#error_log logs/error.log;
#error_log logs/error.log notice;
error_log logs/error.log info;
pid logs/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 5;
#gzip on;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
location /a {
autoindex on; #以页面方式列出整个目录的文件
allow 10.10.0.0/24;
deny all;
#如果不是10.10.0.0/24段的IP访问,重定向至百度网页
if ( $remote_addr !~ "10.10.0" ) {
return http://www.baidu.com;
}
}
error_page 404 /404.html;
location = /404.html {
root html;
}
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
2. 新建目录a,然后在a目录下新建文件,重新加载配置文件
[root@nginx1 html]# mkdir a
[root@nginx1 html]# cd a
[root@nginx1 html]# touch file{a..z}
[root@nginx1 html]# /usr/local/nginx/sbin/nginx -s reload
- 允许的IP访问时,可正常展示出页面
2. 不允许的IP访问时,会重定向至百度网页
3.3 账号密码访问控制
1. 修改 nginx.conf配置文件,添加如下代码
location /b {
auth_basic "欢迎光临";
auth_basic_user_file /usr/local/nginx/html/htpasswd;
}
2. 新建对应的目录和文件,并yum安装httpd-devel工具生成账号密码写到对应的文件里
[root@nginx1 b]# mkdir b
[root@nginx1 b]# echo "welcome to you " > b/index.html
[root@nginx1 b]# yum install httpd-devel
[root@nginx1 b]# htpasswd -cm /usr/local/nginx/htpasswd csw
New password:
Re-type new password:
Adding password for user csw
[root@nginx1 b]#
htpasswd -c
: 创建密码文件,如果文件存在,那么内容被清空重写
htpasswd -m
: 使用MD5加密
3. 访问10.0.0.141/b 页面,弹出账号密码身份验证窗口,输入之前创建的账号密码即可
3.4 新增json格式的access log日志文件
1.在nginx.conf的http全局块里新增如下命令
log_format main_json '{"@timestamp":"$time_local",'
'"client_ip": "$remote_addr",'
'"request": "$request",'
'"status": "$status",'
'"bytes": "$body_bytes_sent",'
'"x_forwarded": "$http_x_forwarded_for",'
'"referer": "$http_referer"'
'}';
access_log logs/access_json.log main_json;
2.重新加载nginx.conf配置文件后,访问http://10.0.0.141页面,观察日志文件的输出
[root@nginx1 conf]# tail -f ../logs/access_json.log
{"@timestamp":"24/Oct/2020:23:59:39 +0800","client_ip": "10.0.0.1","request": "GET / HTTP/1.1","status": "304","bytes": "0","x_forwarded": "-","referer": "-"}
{"@timestamp":"24/Oct/2020:23:59:53 +0800","client_ip": "10.0.0.1","request": "GET /a/ HTTP/1.1","status": "302","bytes": "145","x_forwarded": "-","referer": "-"}
{"@timestamp":"25/Oct/2020:00:00:10 +0800","client_ip": "10.0.0.1","request": "GET /b/ HTTP/1.1","status": "304","bytes": "0","x_forwarded": "-","referer": "-"}
^C
[root@nginx1 conf]#
3.5 防盗链测试
1.新增一台虚拟机,IP为10.0.0.151,安装并启动httpd服务,在/var/www/html目录下新增index.html文件
[root@nginx2 html]# pwd
/var/www/html
[root@nginx2 html]# more index.html
<html>
<head>
<title>it is for test</title>
</head>
<body>
<font size ="5">
<a href="http://10.0.0.141/0.png">dao lian</a>
<br> </br>
</font>
</body>
</html>
[root@nginx2 html]#
2.上传0.png图片至原nginx虚拟机(IP为:10.0.0.141)的/usr/local/nginx/html目录下
[root@nginx1 html]# ls
0.png 404.html 50x.html a b index.html
[root@nginx1 html]#
3.跳出浏览器的开发者模式,访问网址:http://10.0.0.151,并点击daolian超链接,观察到网站地址跳转到了http://10.0.0.141/0.png,请求头信息里包含了referer信息
4.在nginx服务器(10.0.0.141)上修改nginx.conf配置文件,将location / 模块修改为如下
location / {
root html;
index index.html index.htm;
valid_referers none blocked *.ayitula.com;
if ($invalid_referer) {
return 403;
}
}
打开浏览器无痕模式访问http://10.0.0.151,并点击daolian超链接后显示403页面
3.6 基于IP的虚拟主机
1. 在/usr/local/nginx/conf目录下创建一个名为conf.d的目录,然后在conf.d目录下创建虚拟主机配置文件vhost.conf
[root@nginx1 conf.d]# more vhost.conf
server {
listen 10.0.0.141:80;
location /web1 {
root html;
index index.html index.htm index.php;
}
}
server {
listen 10.0.0.142:80;
location /web2 {
root html;
index index.html index.htm;
}
}
2.进入/usr/local/nginx/html目录,创建web1和web2两个目录,并分别在两个目录创建index.html文件
[root@nginx1 html]# mkdir web{1..2}
[root@nginx1 html]# echo "I am web1 " > web1/index.html
[root@nginx1 html]# echo "I am web2 " > web2/index.html
3.编辑 /usr/local/nginx/conf/nginx.conf文件,在server块后引用第一步创建的vhost.conf文件
} # 这里是server块的末尾大括号
include conf.d/vhost.conf;
}
4.添加虚拟子网卡,绑定10.0.0.142IP
[root@nginx1 html]# ifconfig ens33:1 10.0.0.142/24
5.重新加载nginx.conf配置文件,访问http://10.0.0.141/web1和http://10.0.0.142/web2
3.7 基于端口的虚拟主机
1.把3.6中的vhost.conf文件修改为如下,并重新加载nginx即可
[root@nginx1 nginx]# more conf/conf.d/vhost.conf
server {
listen 8081;
location / {
root html/web1;
index index.html index.htm index.php;
}
}
server {
listen 8082;
location / {
root html/web2;
index index.html index.htm;
}
}
[root@nginx1 nginx]#
2.效果如下
3.8 基于域名的虚拟主机
1.修改conf.d/vhost.conf文件,并重新加载nginx配置
[root@nginx1 nginx]# more conf/conf.d/vhost.conf
server {
listen 8081;
server_name web1.nginx.com;
location / {
root html/web1;
index index.html index.htm index.php;
}
}
server {
listen 8082;
server_name web2.nginx.com;
location / {
root html/web2;
index index.html index.htm;
}
}
[root@nginx1 nginx]# /usr/local/nginx/sbin/nginx -s reload
2. 修改要访问的客户端电脑的host文件,添加两条记录
10.0.0.141 web1.nginx.com
10.0.0.141 web2.nginx.com
3.效果如下
3.9 反向代理
1.将之前创建的conf.d/vhost.conf文件修改为如下,重新加载配置文件
[root@nginx1 nginx]# more conf/conf.d/vhost.conf
server {
listen 80;
location / {
index index.html index.htm index.php;
proxy_pass http://10.0.0.151 ;
#下面为反向代理的优化,如不需要可去掉
proxy_set_header Host $host; #修改请求头,添加Host字段
proxy_set_header X-Real-IP $remote_addr; #修改请求头,添加X-Real-IP字段
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #修改请求头,添加X-Forwarded-For字段
client_max_body_size 10m; #允许客户端请求的最大单文件字节数
client_body_buffer_size 128k; #缓冲区代理缓冲用户端请求的最大字节数,
proxy_connect_timeout 90; #nginx跟后端服务器连接超时时间\(代理连接超时\)
proxy_send_timeout 90; #后端服务器数据回传时间\(代理发送超时\)
proxy_read_timeout 90; #连接成功后,后端服务器响应时间\(代理接收超时\)
proxy_buffer_size 4k; #设置代理服务器(nginx)保存用户头信息的缓冲区大小
proxy_buffers 4 32k; #proxy_buffers缓冲区,网页平均在32k以下的话,这样设置
proxy_busy_buffers_size 64k; #高负荷下缓冲大小(proxy_buffers*2)
proxy_temp_file_write_size 64k; #设定缓存文件夹大小,大于这个值,将从upstream服务器传
}
}
[root@nginx1 nginx]#
2.修改之前第3.5节新建的虚拟主机(IP:10.0.0.151)/var/www/html/目录下的index.html
[root@nginx2 html]# echo “This is a haproxy_nginx test” > index.html
3.修改10.0.0.151虚拟主机下的httpd配置文件,将196行的logFormat新增参数%{X-Real-Ip}i ,即记录下真实的客户端访问IP,然后重启httpd服务
196 LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %{X-Real-Ip}i " combined
4.效果如下
10.0.0.1
为我的客户端地址
3.10 nginx 限速
1.限速的定义
限速
(rate limiting)是NGINX众多特性中最有用的,也是经常容易被误解和错误配置的,特性之一访问请求限速。该特性可以限制某个用户在一个给定时间段内能够产生的HTTP请求数。请求可以简单到就是一个对于主页的GET请求或者一个登陆表格的POST请求。用于安全目的上,比如减慢暴力密码破解攻击。通过限制进来的请求速率,并且(结合日志)标记出目标URLs来帮助防范DDoS攻击。
可细分为以下三种:
- 下载速度限速
- 单位时间内请求数限制
- 基于客户端的并发连接限速
Nginx官方版本限制IP的连接和并发分别有两个模块:
limit_req_zone
:用来限制单位时间内的请求数,即速率限制,采用的漏桶算法 “leaky bucket”。limit_conn_zone
:用来限制同一时间连接数,即并发限制。
2、应用场景
下载限速:限制现在速度及并发连接数,应用在下载服务器中,保护带宽及服务器的IO资源。
请求限速:限制单位时间内用户访问请求,防止恶意攻击,保护服务器及资源安全。
3.限速实操
要求:
1、限制web服务器请求处理为1秒一个,触发值为5;
2、限制并发连接数为1;
3、限制下载速度为100K Byte/s.
步骤一:
修改/usr/local/nginx/conf/nginx.conf配置文件,在http块新增两句指令
limit_conn_zone $binary_remote_addr zone=lmt:10m;
limit_req_zone $binary_remote_addr zone=csw:10m rate=1r/s;
然后在server块新增location /csw
location /csw {
limit_req zone=csw burst=5 nodelay;
limit_conn lmt 1;
autoindex on;
limit_rate 100k;
}
步骤二:
在/usr/local/nginx/html目录下新建csw子目录,再在子目录/usr/local/nginx/html/csw/下新建文件index.html,内容为:test for nginx
步骤三:使用dd 命令新建一个300M的文件做下载测速所用
[root@nginx1 csw]# dd if=/dev/zero of=/usr/local/nginx/html/csw/bigfile bs=1M count=300
4.下面为本次实操所涉及到的nginx.conf配置部分
#keepalive_timeout 0;
keepalive_timeout 5;
#gzip on;
#基于IP做连接限制 限制同一IP并发为1 下载速度为100K
limit_conn_zone $binary_remote_addr zone=lmt:10m;
#基于IP对下载速率做限制 限制每秒处理1次请求,对突发超过5个以后的请求放入缓存区
limit_req_zone $binary_remote_addr zone=csw:10m rate=1r/s;
server {
listen 80;
server_name localhost;
location /csw {
limit_req zone=csw burst=5 nodelay;
limit_conn lmt 1;
autoindex on;
limit_rate 100k;
}
}
5.重要参数解释
limit_req_zone $binary_remote_addr zone=csw:10m rate=1r/s;
第一个参数: $binary_remote_addr 表示通过remote_addr这个标识来做限制,“binary_”的目的是缩写内存占用量,是限制同一客户端ip地址。
第二个参数:zone=csw:10m表示生成一个大小为10M,名字为csw的内存区域,用来存储访问的频次信息。
第三个参数:rate=1r/s表示允许相同标识的客户端的访问频次,这里限制的是每秒1次,还可以有比如30r/m的。
limit_req zone=csw burst=5 nodelay;
第一个参数:zone=csw 设置使用哪个配置区域来做限制,与上面limit_req_zone 里的name对应。
第二个参数:burst=5,重点说明一下这个配置,burst爆发的意思,这个配置的意思是设置一个大小为5的缓冲区当有大量请求(爆发)过来时,超过了访问频次限制的请求可以先放到这个缓冲区内。
第三个参数:nodelay,如果设置,超过访问频次而且缓冲区也满了的时候就会直接返回503,如果没有设置,则所有请求会等待排队。
3.11 URL重写
1.URL重写定义:
Rewrite功功能是Nginx服务器提供的一个重要功能。几乎是所有的web产品必备技能,用于实现URL重写。URL重写是非常有用的功能,比如它可以在我们在改变网站结构后,不需要客户端修改原来的书签,也不需要其他网站修改对我们网站的友情链接,还可以在一定程度上提高网站的安全性,能够让我们的网站显得更专业。
2.rewrite概念理解
rewrite是实现URL重写的关键指令,根据regex(正则表达式)部分内容,重定向到replacement,结尾是flag标记。
rewrite <regex> <replacement> [flag];
关键字 正则 替代内容 flag标记
关键字:其中关键字error_log不能改变
正则:perl兼容正则表达式语句进行规则匹配
替代内容:将正则匹配的内容替换成replacement
flag标记:rewrite支持的flag标记
flag标记说明:
last #本条规则匹配完成后,继续向下匹配新的location URI规则
break #本条规则匹配完成即终止,不再匹配后面的任何规则
url重写后,直接使用当前资源,不再执行location里余下的语句,完成本次请求,地址栏url不变
redirect #返回302临时重定向,浏览器地址会显示跳转后的URL地址
permanent #返回301永久重定向,浏览器地址栏会显示跳转后的URL地址
3.常用正则表达式说明
字符 | 描述 |
---|---|
\ | 将后面接着的字符标记为一个特殊字符或一个原义字符或一个向后引用。如“\n”匹配一个换行符,而“ \$ ”则匹配“$” |
^ | 匹配输入字符串的起始位置 |
$ | 匹配输入字符串的结束位置 |
* | 匹配前面的字符零次或多次。如“ol”能匹配“o”(0次)及“ol”(1次)、“oll” (2次)* |
+ | 匹配前面的字符一次或多次。如“ol+”能匹配“ol”及“oll”、“oll”,但不能匹配“o” |
? | 匹配前面的字符一次或多次。如“ol+”能匹配“ol”及“oll”、“oll”,但不能匹配“o” |
+ | 匹配前面的字符零次或一次,例如“do(es)?”能匹配“do”或者“does”,"?“等效于”{0,1}" |
. | 匹配除“\n”之外的任何单个字符,若要匹配包括“\n”在内的任意字符,请使用诸如“[.\n]”之类的模式。 |
(pattern) | 匹配括号内pattern并可以在后面获取对应的匹配,常用$0…$9属性获取小括号中的匹配内容,要匹配圆括号字符需要(Content),如果正则表达式是(\d{3})(\d{2})(\d*)(\d{4}),则$1对应的是正则中(\d{3})匹配到的结果 |
$2对应的是正则中(\d{2})匹配到的结果
4.实操例子
要求
:访问learning.123.com时跳转到 csw.234.com/learning ,而访问sleeping.123.com时就跳转到csw.234.com/sleeping ,浏览器地址栏要求同步改变
准备
:一台nginx服务器(IP:10.0.0.141,域名:learning.123.com和sleeping.123.com),一台apache服务器(IP:10.0.0.151,对应域名 csw.234.com)
4.1、nginx配置部分:
location / {
if ($http_host ~ ^(learning) ){
set $action learning;
rewrite ^/$ http://csw.234.com/$action;
}
if ($http_host ~ ^(sleeping) ){
set $action sleeping;
rewrite ^/$ http://csw.234.com/$action;
}
}
4.1.1 http请求头含义
$http_host
: http请求头中的域名信息
其余的还有:
HTTP_USER_AGENT
: 用户使用的代理,例如浏览器;
HTTP_REFERER
: 告知服务器,从哪个页面来访问的;
HTTP_COOKIE
: 客户端缓存,主要用于存储用户名和密码等信息;
HTTP_HOST
: 匹配服务器ServerName域名;
HTTP_ACCEPT
: 客户端的浏览器支持的MIME类型;
REMOTE_ADDR
: 客户端的IP地址
QUERY_STRING
: URL中访问的字符串;
DOCUMENT_ROOT
: 服务器发布目录;
SERVER_PORT
: 服务器端口;
SERVER_PROTOCOL
: 服务器端协议;
TIME_YEAR
: 年;
TIME_MON
: 月;
TIME_DAY
: 日;
4.1.2 条件匹配字符
条件匹配字符共有6种,具体如下:
- 模糊匹配
~ : 匹配
!~ : 不匹配
~* :不区分大小写的匹配 - 精确匹配
= :精确匹配
!= :精确不匹配
5. rewrite 中last用法例子
nginx配置部分
location / {
if ($http_host ~ ^(learning) ){
rewrite ^/$ http://learning.123.com/csw last ;
}
}
location /csw {
limit_req zone=csw burst=5 nodelay;
limit_conn lmt 1;
autoindex on;
limit_rate 100k;
}
3.12 Nginx优化
1.设置大并发
1.1 设置工作进程与CPU核数一致
- 查看服务器CPU核数:
Last login: Thu Nov 5 22:00:06 2020 from 10.0.0.1
[root@nginx1 ~]# cat /proc/cpuinfo | grep processor
processor : 0
processor : 1
[root@nginx1 ~]#
- 有两核,所以我们可以设置工作进程为2:
user www;
worker_processes 2;
1.2 设置一个CPU核只跑一个工作进程:
#指定运行的核的编号,采用掩码的方式设置编号
worker_cpu_affinity 01 10 ;
- 验证结果
[root@nginx1 ~]# ps -eo psr,command
0 sleep 60
1 nginx: master process /usr/local/nginx/sbin/nginx
0 nginx: worker process
1 nginx: worker process
0 ps -eo psr,command
[root@nginx1 ~]#
2.开启长连接
keepalive_timeout 0;
# 0代表关闭
keepalive_timeout 5;
# 5秒后超时,长连接关闭
keepalive_requests 8192;
# 每个长连接可以接受 8192个请求
3.开启gzip压缩
- 往index.html文件写入内容
for i in `seq 1 20 ` ;do cat /etc/passwd >> /usr/local/nginx/html/index.html ; done
- 查看文件大小为1M
[root@nginx1 csw]# du -h /usr/local/nginx/html/index.html
1.0M /usr/local/nginx/html/index.html
[root@nginx1 csw]#
- 往nginx.conf配置文件里添加gzip压缩的相关配置
gzip on;
gzip_proxied any;
gzip_min_length 1k;
gzip_buffers 4 8k;
gzip_comp_level 6;
gzip_types text/plain text/css application/x-javascript application/javascript application/xml;
#启用gzip压缩的最小文件,小于设置值的文件将不会压缩
gzip_min_length 1k;
# gzip 压缩级别,1-9,数字越大压缩的越好,也越占用CPU时间,后面会有详细说明
gzip_comp_level 1;
# 进行压缩的文件类型。javascript有多种形式。其中的值可以在 mime.types 文件中找到。
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png application/vnd.ms-fontobject font/ttf font/opentype font/x-woff image/svg+xml;
# 是否在http header中添加Vary: Accept-Encoding,建议开启
gzip_vary on;
# 禁用IE 6 gzip
gzip_disable "MSIE [1-6]\.";
# 设置压缩所需要的缓冲区大小
gzip_buffers 32 4k;
# 设置gzip压缩针对的HTTP协议版本
gzip_http_version 1.0;
- 压缩后大小为 4.94K Byte
4. 静态缓存
将部分数据缓存在用户本地磁盘,用户加载时,如果本地和服务器的数据一致,则从本地加载。提升用户访问速度,提升体验度。节省公司带宽成本。
- 往nginx.conf配置文件里添加条件匹配,匹配jgp和png结尾的图片进行缓存
location ~* \.(png|jpg)$ {
expires 1h;
}
- 显示缓存一小时