沙滩星空的博客沙滩星空的博客

Nginx基础:location语法

location匹配参数

location有两种匹配规则:

  1. 匹配URL类型,有四种参数可选,也可以不带参数。location [ = | ~ | ~* | ^~ ] uri { … }
  2. 命名location,用@标识,类似于定于goto语句块。location @name { … }
  • 不加任何规则,默认大小写敏感,前缀匹配.
location /index/ {
  ......
}
#http://abc.com/index  [匹配成功]
#http://abc.com/index/index.page  [匹配成功]
#http://abc.com/test/index  [匹配失败]
#http://abc.com/Index  [匹配失败]
# 匹配到所有uri
  • =: 精确匹配
location = /abc/ {
  .....
 }
        
# 只匹配http://abc.com/abc
#http://abc.com/abc [匹配成功]
#http://abc.com/abc/index [匹配失败]
  • ~: 正则匹配,区分大小写
location ~ /Abc/ {
  .....
}
#http://abc.com/Abc/ [匹配成功]
#http://abc.com/abc/ [匹配失败]
  • ~*: 正则匹配,忽略大小写
location ~* /Abc/ {
  .....
}
# 则会忽略 uri 部分的大小写
#http://abc.com/Abc/ [匹配成功]
#http://abc.com/abc/ [匹配成功]
  • ^~: 非正则匹配。uri以某个常规字符串开头,不支持正则。
location ^~ /index/ {
  .....
}
#以 /index/ 开头的请求,都会匹配上
#http://abc.com/index/index.page  [匹配成功]
#http://abc.com/error/error.page [匹配失败]
  • @: nginx内部跳转
location /index/ {
  error_page 404 @index_error;
}
location @index_error {
  .....
}
#以 /index/ 开头的请求,如果链接的状态为 404。则会匹配到 @index_error 这条规则上。

例:

# 此例用NGINX做反向代理。外网请求转发到内部局域网。
# URI地址包含 password, login等关键词时,响应 403

    location ~ .*(index\.jsp|config|password|login).* {
         return 403;
    }

# 使用等号=,精确匹配URI
    location = /ask/vision/ {
        return 403;
    }
    location = /ask/vision {
        return 403;
    }

    location /css {
        proxy_pass http://127.0.0.1:8888/vision/css/;
    }
    location /js {
        proxy_pass http://127.0.0.1:8888/vision/js/;
    }


    location /ask/ {
        proxy_pass http://127.0.0.1:8888/;
        proxy_cookie_path / /ask;
    }
    location / {
         proxy_pass http://127.0.0.1:8888/;
     }

https://zhuanlan.zhihu.com/p/137042956

未经允许不得转载:沙滩星空的博客 » Nginx基础:location语法

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址