小橘子大叔

  • 首页
  • nginx
  • Linux
  • docker
  • Kubernetes
  • Prometheus
  • 生活
  • 文章归档
  • 友情链接
  • Instagram
  • TikTok
  • X
欢迎随时联系本人
  • Mail

nginx配置文件内的条件判断

  • luxy
  • 2023-07-29
  • 3

        问题描述:我想在nginx.conf中增加这样一句话:

if (!-f $request_filename && $request_uri != "")
重启nginx的时候报错:nginx: [emerg] invalid condition。这是因为nginx的配置中不支持if条件的逻辑与&& 逻辑或|| 运算等逻辑运算符 ,而且不支持if的嵌套语法。

解决办法:

         可以用set增加一个变量,如:

   <strong>   </strong>default_type text/html;<strong>
  </strong>    set $count 1;
      if (!-f $request_filename){
                 set $count ${count}1;
               }
     if ($request_uri = ''){

                 set $count ${count}1;
               }
     if ($count = 11){
                  return 200 '<h1>file not found</h1>';
              }

这样就实现了当访问了不存在的文件并且该uri不为空时返回http 200状态码并且在网页显示“file not found”。

当然,若想达到这一功能,还有一种解决办法,直接加一个新的location

<strong> </strong>location ~ /[^""] {
                        default_type text/html;
                        return 200 '<h1>file not found</h1>';

       }

使用正则表达式,把所有根后非空的字符串都 return 200 '<h1>file not found</h1>',注意,由于匹配location是从上到下匹配的,所以应尽量把这一串代码放到最后充当最后一个匹配规则。

© 2025 小橘子大叔
Theme by Wing
  • {{ item.name }}
  • {{ item.name }}