nginx动静分离:
动:动态资源,例如查询的数据库数据
静:静态资源,例如图片、视频等
location的五种匹配策略
1、匹配符
匹配符 | 匹配规则 | 优先级 |
---|---|---|
= | 精确匹配 | 1 |
* | 匹配以什么字符开头 | 2 |
~ | 区分大小写的正则匹配 | 3 |
~* | 不区分大小写的正则匹配 | 3 |
/ | 匹配所有内容 | 4 |
1.先执行server块的rewrite指令
2.其次执行location匹配规则
3.最后执行location中的rewrite
2、简单使用
web02:
vim /etc/nginx/conf.d/location.conf
server {
server_name location.test.com;
listen 80;
location / {
# 指定解析当前内容的类型
default_type text/html;
# 返回内容 状态码 具体内容
return 200 "location /";
}
location = /status {
# 指定解析当前内容的类型
default_type text/html;
# 返回内容 状态码 具体内容
return 200 "location =";
}
location ~ \.md$ {
# 指定解析当前内容的类型
default_type text/html;
# 返回内容 状态码 具体内容
return 200 "location ~";
}
}
测试:
http://192.168.15.8/
http://192.168.15.8/status
http://192.168.15.8/
3、实现动静分离
一个location代理html
一个location代理图片
web02:
cd /usr/share/nginx/html5-mario/
mv ../images/ /usr/share/nginx/
vim /etc/nginx/conf.d/game1.conf
server{
server_name game1.test.com;
listen 80;
location / {
root /usr/share/nginx/html5-mario;
index index.html;
}
location ~* \.(png|gif|jpg|jpeg|mp4|mp3)$ {
root /usr/share/nginx;
}
}
四种重定向策略
1、last 和 break
last 本条规则匹配完成后,停止匹配,不再匹配后面的规则
break 本条规则匹配完成后,停止匹配,不再匹配后面的规则
区别:
last 是在Nginx内部按照重定向的规则重新访问一遍
break 是在Nginx内部按照重定向的规则去对应的目录访问
2、redirect 和permanent:
redirect 返回302临时重定向,地址栏会显示跳转后的地址
permanent 返回301永久重定向,地址栏会显示跳转后的地址
区别:
临时重定向浏览器不记录缓存
永久重定向浏览器是会记录缓存,再一次访问将不走Nginx服务端,直接在浏览器端跳转。
3、知识储备
nginx配置:
rewrite : 重写URL地址
格式:
rewrite [匹配内容] [重定向到的内容] [重定向规则];
return [状态码] [重定向到的URL]
4、服务器准备
主机 | ip | 身份 |
---|---|---|
web02 | 192.168.15.8 | web服务器 |
案例1:要求访问192.168.15.8,临时重定向到百度
vim /etc/nginx/conf.d/test.conf
server {
server_name ;
listen 80;
location / {
rewrite (.*) https://www.baidu.com redirect;
}
}
重启nginx并测试:
http://192.168.15.8/
案例2:要求访问192.168.15.8,永久重定向到百度
vim /etc/nginx/conf.d/test.conf
server {
server_name ;
listen 80;
location / {
rewrite (.*) https://www.baidu.com permanent;
}
}
重启nginx并测试:
http://192.168.15.8/
案例3:要求访问192.168.15.8/last,重定向到192.168.15.8/test
vim /etc/nginx/conf.d/test.conf
server {
server_name ;
listen 80;
# 解决乱码
charset utf-8;
location = /last {
rewrite (.*) /test last;
}
location = /test {
default_type text/html;
return 200 "test";
}
location / {
default_type text/html;
return 200 "默认";
}
}
重启nginx并测试:
http://192.168.15.8/last
案例4:要求访问192.168.15.8/break,重定向到192.168.15.8下面的test目录。
vim /etc/nginx/conf.d/test.conf
server {
server_name ;
listen 80;
# 解决乱码
charset utf-8;
root /opt;
location /break/ {
rewrite /break/(.*) /test/$1 break;
}
location / {
default_type text/html;
return 200 "默认";
}
}
cd /opt/
mkdir test
cd test
echo "break" > index.html
重启nginx并测试:
http://192.168.15.8/break/index.html