nginx配置选项try_files详解

nginx配置选项try_files详解

一.

try_files是nginx中http_core核心模块所带的指令,主要是能替代一些rewrite的指令,提高解析效率。官网的文档为Module ngx_http_core_module

二.

  1.try_files的语法规则:

    格式1:try_files file ... uri;  格式2:try_files file ... =code;

    可应用的上下文:server,location段

  2.try_files的语法解释:(先贴出官方的解释,楼主再解释下)

Checks the existence of files in the specified order and uses the first found file for request processing; the processing is performed in the current context. The path to a file is constructed from the fileparameter according to the root and alias directives. It is possible to check directory’s existence by specifying a slash at the end of a name, e.g. “$uri/”. If none of the files were found, an internal redirect to the uri specified in the last parameter is made. 

  关键点1:按指定的file顺序查找存在的文件,并使用第一个找到的文件进行请求处理

  关键点2:查找路径是按照给定的root或alias为根路径来查找的

  关键点3:如果给出的file都没有匹配到,则重新请求最后一个参数给定的uri,就是新的location匹配

  关键点4:如果是格式2,如果最后一个参数是 = 404 ,若给出的file都没有匹配到,则最后返回404的响应码

 3.举例说明:

location /images/ {
    root /opt/html/;
    try_files $uri   $uri/  /images/default.gif; 
}
比如 请求 127.0.0.1/images/test.gif 会依次查找 1.文件/opt/html/images/test.gif   2.文件夹 /opt/html/images/test.gif/下的index文件  3. 请求127.0.0.1/images/default.gif

4.其他注意事项
1.try-files 如果不写上 $uri/,当直接访问一个目录路径时,并不会去匹配目录下的索引页  即 访问127.0.0.1/images/ 不会去访问  127.0.0.1/images/index.html 

三.

其他用法:

location / {
    try_files /system/maintenance.html
              $uri $uri/index.html $uri.html
              @mongrel;
}

location @mongrel {
    proxy_pass http://mongrel;
}

以上中若未找到给定顺序的文件,则将会交给location @mongrel处理(相当于匹配到了@mongrel来匹配)

  • 34
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
nginxtry_files指令用于在处理请求时进行文件查找并执行不同的操作。它的语法如下: ``` try_files file ... uri; ``` 其中,`file`是要查找的文件路径,可以是绝对路径或相对路径。`uri`是要重写的URI或转发的URI。 当接收到一个请求时,Nginx会按照try_files指令中的顺序依次查找文件。如果找到了指定的文件,Nginx会返回该文件的内容。如果找不到文件,则会将请求重写为指定的URI,并继续查找。如果最后一个URI也找不到文件,则会返回404错误页面。 举个例子,假设我们有一个目录结构如下: ``` - /var/www/html/ - index.html - images/ - logo.png ``` 我们可以使用try_files指令来配置Nginx: ``` location / { try_files $uri $uri/ /index.html; } location /images/ { try_files $uri $uri/ =404; } ``` 在上面的配置中,如果请求的URI匹配到`/images/`,Nginx会先尝试查找该URI对应的文件。如果找到了文件,比如`/images/logo.png`存在,则会返回该文件。如果找不到文件,则会继续尝试查找`/images/logo.png/`这样的目录。如果目录也不存在,则会返回404错误。 对于其他请求,比如`/about`,Nginx会先尝试查找该URI对应的文件。如果找到了文件,比如`/var/www/html/about`存在,则会返回该文件。如果找不到文件,则会继续尝试查找`/var/www/html/about/`这样的目录。如果目录也不存在,则会返回`/var/www/html/index.html`文件的内容。 总之,try_files指令提供了一种方便的方式来处理文件查找和请求重写,使得我们能够更灵活地配置Nginx的行为。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值