Location 使用详解
语法规则:location [=||*|^~] /uri/ {…}
= # 用于标准uri前,需要请求字符串与uri精确匹配,如果匹配成功就停止向下匹配并立即处理请求。
~ # 用于标准uri前,表示包含正则表达式并且区分大小写,并且匹配
!~ # 用于标准uri前,表示包含正在表达式并且不区分大小写,并且不匹配
~* #用于标准uri前,表示包含正则表达式并且不区分大小写,并且匹配
!~* #用于标准uri前,表示包含正则表达式并且不区分大小写,并且不匹配
^~ # 用于标准uri前,表示包含正则表达式并且匹配以什么开头
$ # 用于标准uri前,表示包含正则表达式并且匹配以什么结尾
\ # 用于标准uri前,表示包含正则表达式并且转义字符。可以转. * ? 等
* # 用于标准uri前,表示包含正则表达式并且代表任意长度的任意字符
示例一:
[root@centos7-3 conf]# vim /data/usr/local/nginx/conf/conf.d/locatest.conf
server {
listen 80;
server_name www.jyc.net;
location / {
root /data/jyc;
index index.html;
}
location = /1.txt {
root /data/jyc/text;
index index.html;
}
}
准备页面:
[root@centos7-3 conf]# cd /data/jyc/
[root@centos7-3 jyc]# ll
total 4
-rw-r–r-- 1 root root 24 Jun 27 09:26 index.html
drwxr-xr-x 2 root root 19 Jun 27 09:26 text
[root@centos7-3 jyc]# cd text/
[root@centos7-3 text]# ll
total 4
-rw-r–r-- 1 root root 26 Jun 27 09:26 1.txt
页面测试
root@ubuntu-1:~# curl www.jyc.net
jyc page 192.168.48.143
root@ubuntu-1:~# curl www.jyc.net/1.txt #当uri匹配1.txt的时候,优先选择该location
1.txt page 192.168.48.143
示例二:
server {
listen 80;
server_name www.jyc.net;
location ^~ /image { ##表示以image开通
root /data/jyc;
index index.html;
}
location /image1 { ##精确匹配
root /data/jyc;
index index.html;
}
}
测试
root@ubuntu-1:~# curl www.jyc.net/image/
image page 192.168.48.143
root@ubuntu-1:~# curl www.jyc.net/image1/ ##当精确的时候,优先于正则表达式
image1 page 192.168.48.143
示例三:测试包含什么关键字的匹配顺序
server {
listen 80;
server_name www.jyc.net;
location / { ##
root /data/jyc;
index index.html;
}
location ~* .(jpg|tif) {
root /data/jyc/image1;
index index.html;
}
}
示例:
root@ubuntu-1:~# curl www.jyc.net/
jyc page 192.168.48.143
root@ubuntu-1:~# curl www.jyc.net/1.jpg
1.jpc 192.168.48.143
匹配优先级:
= > ^~ > ~ / ~* > /