【问题标题】:How to get NGINX to execute all URL's in a folder via index.php如何让 NGINX 通过 index.php 执行文件夹中的所有 URL
【发布时间】:2019-08-11 18:12:15
【问题描述】:

我已经为此搜索了大量的答案,但找不到合适的答案。

基本上,我有一个在 NGINX 上运行的 SilverStripe 内置网站。这一切都很好,但我希望通过管理员上传的任何文件/图像(到资产文件夹)通过站点根目录中的 index.php 解析(因此我们可以在返回之前检查管理员中设置的文件的权限)给用户)。

我有一个非常简单的 nginx 配置(用于我的本地 docker 实例):

server {
  include mime.types;
  default_type  application/octet-stream;
  client_max_body_size 0;
  listen 80;
  root /var/www/html;

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

  location ^~ /assets/ {
      try_files $uri /index.php?$query_string;
  }

  location /index.php {
    fastcgi_buffer_size 32k;
    fastcgi_busy_buffers_size 64k;
    fastcgi_buffers 4 32k;
    fastcgi_keep_conn on;
    fastcgi_pass   php:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include        fastcgi_params;
  }
}

问题在于以下几行:

  location ^~ /assets/ {
      try_files $uri /index.php?$query_string;
  }

不幸的是,try_files 在将请求交给 php 之前会检查文件是否存在。有没有办法阻止这种情况并将资产目录中的所有请求直接交给 PHP?

【问题讨论】:

  • 尝试删除$uri,这样它就不会寻找它。虽然我不确定$query_string 是否会有所帮助,但您是否打算将 $uri 作为 GET 参数传递给 PHP?
  • 我确实尝试过这个,但正如下面的答案所述,try_files 需要两个参数。我确实设法通过使用 try_files /index.php?$query_string /index.php?$query_string; 来捏造它

标签: php nginx silverstripe


【解决方案1】:

try_files 需要两个参数,因此您可以使用虚拟值来替换 file 术语。例如:

try_files nonexistent /index.php$is_args$args;

详情请见this document


但更简洁的解决方案可能是 rewrite...last 声明:

rewrite ^ /index.php last;

rewrite 指令将自动附加查询字符串。详情请见this document

【讨论】:

  • 完美!重写就像一个魅力。我确实认为rewrite 可能是答案,我没有意识到查询字符串是自动附加的。
【解决方案2】:

在我看来,只是盲目地将所有内容传递给正确的脚本是 做正确的事。

location /assets/ {
    include       fastcgi_params;
    fastcgi_param SCRIPT_NAME /index.php;
    fastcgi_param SCRIPT_FILENAME $document_root/index.php;
    fastcgi_pass  php:9000;
}

【讨论】:

    猜你喜欢
    • 2015-05-30
    • 2016-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    • 2013-11-14
    • 2011-05-02
    • 2018-06-20
    相关资源
    最近更新 更多