首页 > 开发 > Nginx > 正文

nginx location语法使用介绍

2020-07-28 15:52:46
字体:
来源:转载
供稿:网友
Nginx 中的 Location 指令 是NginxHttpCoreModule中重要指令。Location 指令,是用来为匹配的 URI 进行配置,URI 即语法中的”/uri/”,可以是字符串或正则表达式。但如果要使用正则表达式,则必须指定前缀

nginx location介绍

Nginx 中的 Location 指令 是NginxHttpCoreModule中重要指令。Location 指令,是用来为匹配的 URI 进行配置,URI 即语法中的”/uri/”,可以是字符串或正则表达式。但如果要使用正则表达式,则必须指定前缀。

nginx location语法

基本语法:location [=|~|~*|^~] /uri/ { … }

= 严格匹配。如果这个查询匹配,那么将停止搜索并立即处理此请求。
~ 为区分大小写匹配(可用正则表达式)
~* 为不区分大小写匹配(可用正则表达式)
!~和!~*分别为区分大小写不匹配及不区分大小写不匹配
^~ 如果把这个前缀用于一个常规字符串,那么告诉nginx 如果路径匹配那么不测试正则表达式。

nginx location应用实例

location = / {# 只匹配 / 查询。}
location / {# 匹配任何查询,因为所有请求都已 / 开头。但是正则表达式规则和长的块规则将被优先和查询匹配。}
location ^~ /images/ {# 匹配任何已 /images/ 开头的任何查询并且停止搜索。任何正则表达式将不会被测试。}
location ~* /.(gif|jpg|jpeg)$ {# 匹配任何已 gif、jpg 或 jpeg 结尾的请求。}
location ~* /.(gif|jpg|swf)$ { valid_referers none blocked start.igrow.cn sta.igrow.cn; if ($invalid_referer) { #防盗链 rewrite ^/ http://$host/logo.png; }}
 location ~* /.(js|css|jpg|jpeg|gif|png|swf)$ {if (-f $request_filename) {  #根据文件类型设置过期时间  expires  1h;  break;}}
 location ~* /.(txt|doc)${ #禁止访问某个目录  root /data/www/wwwroot/linuxtone/test;  deny all;}

以下是补充:

Nginx Location基本语法

location

syntax: location [=|~|~*|^~] /uri/ { … }
语法:location [=|~|~*|^~] /uri/ { … }

default: no
默认:否

context: server
上下文:server

This directive allows different configurations depending on the URI. It can be configured using both conventional strings and regular expressions. To use regular expressions, you must use the prefix ~* for case insensitive match and ~ for case sensitive match.
这个指令随URL不同而接受不同的结构。你可以配置使用常规字符串和正则表达式。如果使用正则表达式,你必须使用 ~* 前缀选择不区分大小写的匹配或者 ~ 选择区分大小写的匹配。

To determine which location directive matches a particular query, the conventional strings are checked first. Conventional strings match the beginning portion of the query and are case-sensitive - the most specific match will be used (see below on how nginx determines this). Afterwards, regular expressions are checked in the order defined in the configuration file. The first regular expression to match the query will stop the search. If no regular expression matches are found, the result from the convention string search is used.

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表