【问题标题】:nginx "try_files" directive is not allowed here此处不允许使用 nginx“try_files”指令
【发布时间】:2014-10-08 04:06:40
【问题描述】:

我想要实现的很简单:

如果子域以admin 开头,请尝试直接从控制器admin.php 提供服务,对于所有其他情况,请尝试使用site.php 提供文件。

请注意,我不知道域名,因为很多域名都指向我们。 到目前为止我尝试了什么:

server {
    listen 8080;
    root /path/to/current/web;

    location / {
        if ($http_host ~ "^admin") {
            try_files $uri @rewriteadmin;
        }
        if ($http_host !~ "^admin") {
            try_files $uri @rewriteapp;
        }
    } 

    location @rewriteapp {
        rewrite ^(.*)$ /site.php/$1 last;
    }

    location @rewriteadmin {
        rewrite ^(.*)$ /admin.php/$1 last;
    }
    ...
 }

当然,这个设置不起作用并给了我:[emerg] "try_files" directive is not allowed here

请问实现这一目标的最佳做法是什么?

【问题讨论】:

    标签: nginx vhosts


    【解决方案1】:

    快速回答:try_files 需要在 location 内。

    快速修复:

    location / {
        try_files $uri $uri/ /index.php?$args;
    }
    

    适用于我的 CakePHP v 3.x

    【讨论】:

      【解决方案2】:

      您可以在server_name 中使用正则表达式。所以最好使用两个服务器块。

      server {
          listen 8080 default_server;
          root /path/to/current/web;
      
          location / {
              try_files $uri @rewriteapp;
          } 
      
          location @rewriteapp {
              rewrite ^(.*)$ /site.php/$1 last;
          }
      
          ...
      }
      
      server {
          listen 8080;
          server_name ~^admin;
          # or better, if they all starts with "admin." token
          # server_name admin.*;
          root /path/to/current/web;
      
          location / {
              try_files $uri @rewriteadmin;
          } 
      
          location @rewriteadmin {
              rewrite ^(.*)$ /admin.php/$1 last;
          }
      
          ...
      }
      

      【讨论】:

      • 相当,是的。否则 nginx 可以选择默认管理服务器(它不应该,但任何事情都会发生)。没关系,如果您将其他服务器设置为默认服务器,请确保它不是处理管理员请求的服务器。
      • 是的,抱歉我在你回答之前删除了我的问题,因为我在网上找到了解释。为了给别人留下痕迹,我在问default_server 的重要性。谢谢。
      猜你喜欢
      • 2019-03-16
      • 2015-01-08
      • 1970-01-01
      • 2020-10-03
      • 2013-12-23
      • 2015-06-29
      • 1970-01-01
      • 1970-01-01
      • 2021-08-06
      相关资源
      最近更新 更多