引言:大家好,我是热爱coding,崇尚开源,乐于分享的【皮卡丘的猫】
相信大家在使用nginx过程中,nginx.conf 里面的location 配置可能还一知半解,本篇文章尽可能让你熟悉如何去配置使用location之妙法。
话不多说,先上原始的server块配置
server {
listen 89;
server_name localhost;
location / {
root html;
index test.html;
}
}
首先大家肯定知道,在地址栏输入http://xx:89 。默认的是寻找html目录下的test.html文件。假如服务器路径为:/home/test/files/img/test.png,可以修改配置如下
server {
listen 89;
server_name localhost;
location /test {
root /home;
}
}
在地址栏输入的是:http:xx:89/test/xx.png,定位到服务器寻找的拼接目录是从/home/test 寻找静态资源 ,为了对前端进行透明,root 可以换种别名的方式来处理,再比如:
server {
listen 89;
server_name localhost;
location /static {
alias /home/test;
}
}
这样,通过别名的方式前端就不知道后端静态资源所在目录位置了。
接下来讲一下location的匹配规则解析
-
空格:默认匹配,普通匹配
location / { root /home; }
-
=:精确匹配
location = /test/img/face1.png { root /home; }
-
~*:匹配正则表达式,不区分大小写
# 符合图片的显示 location ~* .(GIF|jpg|png|jpeg) { root /home; }
-
~:匹配正则表达式,区分大小写
# GIF必须大写才能匹配到 location ~ .(GIF|jpg|png|jpeg) { root /home; }
-
^~:以某个字符路径开头
location ^~ /test/img { root /home; }
至此,location的用法就讲完了,大家可以去实操一下吧。