【2022】Nginx之location-module使用

简介: 【2022】Nginx之location-module使用

location的作用是根据相应的规则处理流量请求。

location说明

location语法:

location [ = | ~ | ~* | ^~ | ] uri { ... }
location @name { ... }
context: server,location

以上各项含义:

location:定义具体的URI如何响应
=、~、~*、^~:用于URI匹配
@:用于创建一个内部location标识,只供内部匹配
还有一种是当以上所有都不符合时,默认会匹配“/”

各修饰符含义:

=:精确匹配
~:区分大小写的正则表达式
~*:不区分大小的正则表达式
^~:不使用正则表达式

location匹配规则

nginx使用最长匹配原则匹配前缀location,在前缀location中,顺序无关紧要。

location查找逻辑:

3d46e9b7a1454bf3a60e44980ea173ef.png

location示例说明

假如我们有一个域名是www.yyang.com,那么

  • 匹配“/”
location = / { ... }
  • 匹配“index.html”
location / { ... }
  • 匹配“documents/index.html”
location /documents/ { ... }
  • 匹配“/images/1.gif”
location ^~ /images/ { ... }
  • 匹配“/documents/1.jpg”
location ~* \.(gif|jpg|jpeg)$ { ... }
  • 例:如果匹配“= /”那么写作:
http://www.yyang.com/

匹配优先级从高到底分别是:

=大于^~大于~大于~*大于/

location-@ 重定向

location @name 不接受外部请求,只用于内部重定向

  • 示例:
error_page 403 404 @error
location @error {
  return 302 http://$server_name;
}

这个例子是说如果你请求的页面不存在就返回主页。

目录
相关文章
|
应用服务中间件 nginx
配置nginx时加上--without-http_rewrite_module这个参数,就不需要安装pcre
不加--without-http_rewrite_module这个参数时就是启动URL重写,所以需要pcre ./configure --with-http_stub_status_module --without-http_rewrite_module --prefix=/usr/local/n...
2467 0
|
5月前
|
应用服务中间件 nginx
nginx日志模块 ngx_http_log_module
nginx日志模块 ngx_http_log_module
|
应用服务中间件 nginx
nginx--location
nginx--location
|
应用服务中间件 nginx
Nginx专题:location
Nginx专题:location
90 0
|
应用服务中间件 nginx Perl
nginx模块--with-http_realip_module
nginx模块--with-http_realip_module
3612 0
|
前端开发 应用服务中间件 nginx
|
前端开发 应用服务中间件 nginx
|
前端开发 应用服务中间件 nginx
|
应用服务中间件 nginx