Linux location 定位 、重定向

Celeste ·
更新时间:2024-09-20
· 578 次阅读

location 定位 、重定向

server {
listen 80;
server_name localhost;

location / { root html; index index.html index.htm; }

}

location : 定位
语法:
location [=||*|^~] patt {
}
= : 精准匹配
~ : 正则匹配

URI:资源描述符
URL:统一资源定位符
URN:资源目录符
URI=URL+URN
http://XXX.com/image/nginx.png

location / { root /usr/local/nginx/html; index index.html index.htm; } location =/ { root /var/www/html; index index.html index.htm; } 首先先进性精确匹配,拿到index.html 再进行一般匹配:/usr/local/nginx/html/index.html

重定向: rewrite
1.所有访问a.html的请求,重定向到b.html;
location / {
root html;
index index.html index.htm;

#rewrite /a.html /b.html; rewrite /a.html /b.html redirect ; }

2.所有访问192.168.4.5的请求重定向至www.tmooc.cn;

rewrite ^/ http://www.tmooc.cn; location / { root html; index index.html index.htm; #rewrite /a.html /b.html; #rewrite /a.html /b.html redirect ; }

3.所有访问192.168.4.5/下面子页面,重定向至www.tmooc.cn/下相同的页面;
rewrite ^/(.*)$ http://www.tmooc.cn/$1;
#rewrite ^/ http://www.tmooc.cn;
location / {
root html;
index index.html index.htm;

#rewrite /a.html /b.html; #rewrite /a.html /b.html redirect ; }

4.实现firefox与curl访问相同页面文件,返回不同的内容。

#rewrite ^/(.*)$ http://www.tmooc.cn/$1; #rewrite ^/ http://www.tmooc.cn; location / { root html; index index.html index.htm; #rewrite /a.html /b.html; #rewrite /a.html /b.html redirect ; } if ($http_user_agent ~* firefox ) { rewrite ^/(.*)$ /firefox/$1 }

重写中用到的指令
if (条件) {} 设定条件,再进行重写
set #设置变量
return #返回状态码
break #跳出rewrite
rewrite #重写

条件又怎么写?

1: “=”来判断相等, 用于字符串比较 2: “~” 用正则来匹配(此处的正则区分大小写) ~* 不区分大小写的正则 3: -f -d -e来判断是否为文件,为目录,是否存在. last 不再读其他rewrite break 不再读其他语句,结束请求 redirect 临时重定向 permament 永久重定向
作者:Wang cheng zhi



Linux location 重定向 定位

需要 登录 后方可回复, 如果你还没有账号请 注册新账号