Nginx location的匹配规则
~ 波浪线表示执行一个正则匹配,区分大小写
~* 表示执行一个正则匹配,不区分大小写
^~ ^~表示普通字符匹配,如果该选项匹配,只匹配该选项,不匹配别的选项,一般用来匹配目录
= 进行普通字符精确匹配
@ #"@" 定义一个命名的 location,使用在内部定向时,例如 error_page, try_files
location 匹配优先级
= 精确匹配会第一个被处理。如果发现精确匹配,nginx停止搜索其他匹配。
普通字符匹配,正则表达式规则和长的块规则将被优先和查询匹配,也就是说如果该项匹配还需去看有没有正则表达式匹配和更长的匹配。
^~ 则只匹配该规则,nginx停止搜索其他匹配,否则nginx会继续处理其他location指令。
最后匹配理带有"~"和"~*"的指令,如果找到相应的匹配,则nginx停止搜索其他匹配;当没有正则表达式或者没有正则表达式被匹配的情况下,那么匹配程度最高的逐字匹配指令会被使用。
示例
location = / { # 只匹配"/". [ configuration A ] } } l location / { # 匹配任何请求,因为所有请求都是以"/"开始 # 但是更长字符匹配或者正则表达式匹配会优先匹配 [ configuration B ] } } l location ^~ /images/ { # 匹配任何以 /images/ 开始的请求,并停止匹配 其它location [ configuration C ] } } l location ~* \.(gif|jpg|jpeg)$ { # 匹配以 gif, jpg, or jpeg结尾的请求. # 但是所有 /images/ 目录的请求将由 [Configuration C]处理. [ configuration D ] } }
try_files的用处
location / { root /var/www/build; index index.html index.htm; try_files $uri $uri/ @rewrites; } location @rewrites { rewrite ^(.+)$ /index.html last; }
index的用处
index index.php index.html index.htm i.html;
# index 定义目录默认查找文件的名称 如范文http://www.xxx.com/love 会先查找love文件 没有再查找love目录 如果有 会依次查找love目录下
# index.php index.html index.htm i.html 文件返回
server { listen 80; server_name localhost; root /root/scc/dist; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; # 静态文件,nginx自己处理 location ~* \.(js|css|flash|media|jpg|png|gif|dll|cab|CAB|ico|html|htm|json|txt|mp3)$ { expires 30d; } location / { # index 定义目录默认查找文件的名称 index index.php index.html index.htm i.html; # 匹配任何请求,因为所有请求都是以"/"开始 单页面应用统一指向index.html # 但是更长字符匹配或者正则表达式匹配会优先匹配 如/api/转发到后端接口 静态资源 # 当用户请求 http://localhost/example 时,这里的 $uri 就是 /example。 # try_files会到硬盘里尝试找这个文件。如果存在名为 /$root/example(其中 $root 是项目代码安装目录)的文件,就直接把这个文件的内容发送给用户。 # 显然,目录中没有叫 example 的文件。然后就看 $uri/,增加了一个 /,也就是看有没有名为 /$root/example/ 的目录。 如果有 在该目录下查找index 默认的文件返回 否则403 # 如果目录又找不到,就会 fall back 到 try_files 的最后一个选项 /index.html,发起一个内部 “子请求”,也就是相当于 nginx 发起一个 HTTP 请求到 http://localhost/index.html。 # 此时 $uri 就是 /index.html 可以在项目根目录找到该文件 匹配成功 try_files $uri $uri/ /index.html; } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } }
原文:https://www.cnblogs.com/shichangchun/p/10990375.html