Nginx 的 location 设置

一,location 介绍

location 是 Nginx中的块级指令(block directive),location 指令的功能是用来匹配不同的 url 请求,进而对请求做不同的处理和响应。

二,localtion URL 匹配类型

1. location = # 精准匹配

2. location ^~ # 带参前缀匹配

3. location ~ # 正则匹配(区分大小写)

4. location ~* # 正则匹配(不区分大小写)

5. location /a # 普通前缀匹配,优先级低于带参数前缀匹配。

6. location / # 任何没有匹配成功的,都会匹配这里处理


三,location 匹配示例:

3.1 “=” ,精确匹配

内容要同表达式完全一致才匹配成功

location = /test/ { ... } 
# 只匹配 http://test.com/test
# http://test.com/test (匹配成功)
# http://test.com/test/index (匹配失败)


3.2 “~”,执行正则匹配,区分大小写。

location ~ /test/ { ... }
#http://test.com/test/ (匹配成功)
#http://test.com/Test/ (匹配失败)


3.3“~*”,执行正则匹配,忽略大小写

location ~* /test/ {...}
#http://test.com/test/ (匹配成功)
#http://test.com/Test/ (匹配成功)


3.4 “^~”,表示普通字符串匹配上以后不再进行正则匹配。

location ^~ /index/ { ... }
#以 /index/ 开头的请求,都会匹配上
#http://test.com/index/index.page (匹配成功)
#http://test.com/error/error.page (匹配失败)


3.5 不加任何规则时,默认是大小写敏感,前缀匹配,相当于加了“~”与“^~”

location /index/ { ... }
#http://test.com/index (匹配成功)
#http://test.com/index/index.page (匹配成功)
#http://test.com/test/index (匹配失败)
#http://test.com/Index (匹配失败)


3.6 “@”,nginx内部跳转

location /index/ {
 error_page 404 @index_error;
}
location @index_error {
 ...
}

以 /index/ 开头的请求,如果链接的状态为 404。 则会匹配到 @index_error 这条规则上。


location /img/ {

 alias /var/www/image/;

}

若按照上述配置的话,则访问/img/目录里面的文件时,ningx会自动去/var/www/image/目录找文件

修改时间 2023-10-31

声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。
真诚赞赏,手留余香
赞赏
随机推荐
CSS 媒体特性 prefers-color-scheme
PHP curl 的用法
WordPress 上传附件
WordPress RESTful API 路由代码结构
视频剪辑软件 Shotcut 笔记
WordPress 获取当前主题文件夹的路径
Git 放弃本地修改,强制和之前的某次提交同步
p 标签里面不能嵌套块级元素