今天讲下location的用法,部分内容是直接从网络上摘取的,这边做了一个整理,为了便于理解和学习,我这边做了一些例子。
语法规则: location [=|~|~*|^~] /uri/ { … }
= 表示精确匹配,这个优先级也是最高的
^~ 表示uri以某个常规字符串开头,理解为匹配 url路径即可。nginx不对url做编码,因此请求为/static/20%/aa,可以被规则^~ /static/ /aa匹配到(注意是空格)。
~ 表示区分大小写的正则匹配
~* 表示不区分大小写的正则匹配(和上面的唯一区别就是大小写)
!~和!~*分别为区分大小写不匹配及不区分大小写不匹配的正则
/ 通用匹配,任何请求都会匹配到,默认匹配.文章源自运维生存时间-https://www.ttlsa.com/nginx/nginx-location-configure/
下面讲讲这些语法的一些规则和优先级
多个location配置的情况下匹配顺序为(参考资料而来,还未实际验证,试试就知道了,不必拘泥,仅供参考):文章源自运维生存时间-https://www.ttlsa.com/nginx/nginx-location-configure/
优先级=>^~>
首先匹配 =,其次匹配^~, 其次是按文件中顺序的正则匹配,最后是交给 / 通用匹配。当有匹配成功时候,停止匹配,按当前匹配规则处理请求。文章源自运维生存时间-https://www.ttlsa.com/nginx/nginx-location-configure/
例子,有如下匹配规则:文章源自运维生存时间-https://www.ttlsa.com/nginx/nginx-location-configure/
location / { echo "/"; //需要安装echo模块才行,这边大家可以改成各自的规则 } location = / { echo "=/"; } location = /nginx { echo "=/nginx"; } location ~ \.(gif|jpg|png|js|css)$ { echo "small-gif/jpg/png"; } location ~* \.png$ { echo "all-png"; } location ^~ /static/ { echo "static"; }
以下是各种的访问情况文章源自运维生存时间-https://www.ttlsa.com/nginx/nginx-location-configure/
访问http://a.ttlsa.com/.因为/是完全匹配的
如下:文章源自运维生存时间-https://www.ttlsa.com/nginx/nginx-location-configure/
# curl http://a.ttlsa.com/ =/
访问http://a.ttlsa.com/nginx,因为完全匹配了"=/nginx"文章源自运维生存时间-https://www.ttlsa.com/nginx/nginx-location-configure/
# curl http://a.ttlsa.com/nginx =/nginx
访问http://a.ttlsa.com/nginx,从第一个开始尝试匹配,最后匹配到了~* \.png$ .文章源自运维生存时间-https://www.ttlsa.com/nginx/nginx-location-configure/
# curl http://a.ttlsa.com/xxx/1111.PNG (注意,这是大写) all-png
访问http://a.ttlsa.com/static/1111.png,虽然static放在最后面,但是因为有^的缘故,他是最匹配的.文章源自运维生存时间-https://www.ttlsa.com/nginx/nginx-location-configure/
# curl http://a.ttlsa.com/static/1111.png static
好了,最后给出我们先上环境的静态文件的匹配规则文章源自运维生存时间-https://www.ttlsa.com/nginx/nginx-location-configure/
location ~* .*\.(js|css)?$ { expires 7d; //7天过期,后续讲解 access_log off; //不保存日志 } location ~* .*\.(png|jpg|gif|jpeg|bmp|ico)?$ { expires 7d; access_log off; } location ~* .*\.(zip|rar|exe|msi|iso|gho|mp3|rmvb|mp4|wma|wmv|rm)?$ { deny all; //禁止这些文件下载,大家可以根据自己的环境来配置 }文章源自运维生存时间-https://www.ttlsa.com/nginx/nginx-location-configure/文章源自运维生存时间-https://www.ttlsa.com/nginx/nginx-location-configure/
4F
这文章错别字太多了,误人子弟!
3F
这是什么啊,你能说明白什么是Location不行啊,这文章写得,
2F
location ~* .*.(js|css)?$
{
expires 7d; //7天过期,后续讲解
access_log off; //不保存日志
}
这里的第一个点“.”和问号 什么理解呢
B1
@ 向前冲向梦追 .*表示任意支付 .一个转义,就是一个点。问号不加也可以
1F
connect() failed (111: Connection refused) while connecting to upstream,这个错误是那里没有配置好?说可以下可能的我来钻研一下
B1
@ eason php-fpm没有运行或者php-fpm的连接队列满来
来自外部的引用