day 42 作业
第41题
概念题:
1.location和rewrite的区别
Nginx location 可以控制访问网站的路径,但是一个server可以有多个location配置。
rewrite 指令可以基于用户请求的RUI通过正则表达式的匹配来进行改写。
rewrite 指令可以存在多条,并且按照次序依次执行
rewrite 指令可以根据flag标志符对指令进一步处理。
如果替换字符串以‘http://’,"https://"或“$scheme”开头,则处理将停止,并将重定向返回到客户端。
rewrite 指令可以作用于server,location,if
2.301和302的区别
301是永久跳转 permanent
302是临时跳转 redirect
3.last和break的区别
last 本条规则匹配完成后,继续向下匹配新的location URI规则
1.last标记在本条规则匹配完成后,对其所在的server标签重新发起修改后的URL请求,再次匹配location
2.使用last和break,浏览器显示的还是原来的URL,由服务器内部完成跳转。
break 本条规则匹配完成即终止,不再匹配后面的任何规则
环境准备:
mkdir /code/blog/iphone -p
mkdir /code/blog/chrome -p
mkdir /code/blog/pc -p
mkdir /code/img/images -p
echo iphoneeeee > /code/blog/iphone/2021-11-25-linux.txt
echo chromeeeee > /code/blog/chrome/2021-11-25-linux.txt
echo pcccccc > /code/blog/pc/2021-11-25-linux.txt
试验题:
iphone用户:
访问 www.oldboy.com/txt/2021/11/25/linux.txt
302跳转 blog.oldboy.com/iphone/2021-11-25-linux.txt
访问内容 iphoneeeee
chrome用户:
访问 www.oldboy.com/txt/2021/11/25/linux.txt
302跳转 blog.oldboy.com/chrome/2021-11-25-linux.txt
访问内容 chromeeeee
其他用户:
访问 www.oldboy.com/txt/2021/11/25/linux.txt
302跳转 blog.oldboy.com/pc/2021-11-25-linux.txt
访问内容 pcccccc
所有用户:
访问: www.oldboy.com/img/2021/11/25/linux.jpg
302跳转 img.oldboy.com/images/2021-11-25-linux.jpg
内部跳转 img.oldboy.com/images/linux-20211125.jpg
if.conf
server {
listen 80 ;
server_name www.oldboy.com;
location /txt {
#客户端类型完全匹配iphone
if ($http_user_agent = iphone) {
rewrite ^/txt/([0-9]+)/([0-9]+)/([0-9]+)/(.*).txt$ http://blog.oldboy.com/iphone/$1-$2-$3-$4.txt redirect;
}
#客户端类型不区分大小写匹配
if ($http_user_agent ~* Chrome) {
rewrite ^/txt/([0-9]+)/([0-9]+)/([0-9]+)/(.*).txt$ http://blog.oldboy.com/chrome/$1-$2-$3-$4.txt redirect;
}
#都没匹配上则执行下面语句
rewrite ^/txt/([0-9]+)/([0-9]+)/([0-9]+)/(.*).txt$ http://blog.oldboy.com/chrome/$1-$2-$3-$4.txt redirect;
}
location /img {
#所有用户
rewrite ^/img/([0-9]+)/([0-9]+)/([0-9]+)/(.*).jpg$ http://img.oldboy.com/images/$1-$2-$3-$4.jpg redirect;
}
}
blog.conf
server {
listen 80;
server_name blog.oldboy.com ;
location /iphone {
root /code/blog/;
index index.html;
}
location /chrome {
root /code/blog/;
index index.html;
}
location /pc {
root /code/blog/;
index index.html;
}
}
img.conf
server {
listen 80;
server_name img.oldboy.com ;
location /images {
root /code/img/;
index index.html;
rewrite ^/img/([0-9]+)/([0-9]+)/([0-9]+)/(.*).jpg$ /images/$4-$1$2$3.jpg break;
}
}