【问题标题】:Rewrite php extension prior to html on nginx在 nginx 上重写 html 之前的 php 扩展
【发布时间】:2016-06-02 13:11:37
【问题描述】:

我正在尝试将无扩展名的服务器请求重写为相应的 php 文件。到目前为止,我设法做到了,但我想在 html 之前重写 php,所以当我必须使用相同文件名的文件时,它首先尝试找到文件的 php 版本,并且只有当它没有' t 以 php 形式存在,尝试以 html 形式找到它。我不知道这是否有意义,我只是想知道是否有可能在 html 文件之前获取文件的 php 版本。我的代码看起来像这样,但如果我在try_files 行中更改@extensionless-php 的位置,则会导致404500 错误。我的代码如下所示:

root path/to/root;
index index.php index.html;

try_files $uri $uri.html $uri/ @extensionless-php;

location ~ \.php$ {
        try_files $uri =404;

        # cgi-params
    }

location @extensionless-php {
        rewrite ^(.*)$ $1.php last;
    }

如果有人知道实现这一点的方法或对此有进一步的意见,请告诉我。

【问题讨论】:

  • 不确定这个问题是否有意义。您正在谈论无扩展请求和重写为 PHP。我看不出 HTML 的来源。
  • 当有两个同名文件,一个以 .html 结尾,一个以 .php 结尾时,HTML 进入。我希望它先重写 php,如果这不起作用(即该文件不存在于“php-version”中),则退回到将其重写为 html。
  • 我建议你更新你的问题,因为它确实澄清了很多问题。

标签: php nginx server


【解决方案1】:

一种可能的方法是从您的try_files 语句中删除$uri.html 子句,并在命名的位置块中尝试这两个扩展。例如:

root path/to/root;
index index.php index.html;

location / {
    try_files $uri $uri/ @rewrite;
}
location ~ \.php$ { ... }

location @rewrite {
    if (-e $request_filename.php) {
        rewrite ^ $uri.php last;
    }
    if (-e $request_filename.html) {
        rewrite ^ $uri.html last;
    }
}

请注意,if 指令带有以下 safety warnings

【讨论】:

  • 这或多或少是我想要的。谢谢。
猜你喜欢
  • 2015-07-08
  • 1970-01-01
  • 1970-01-01
  • 2016-03-06
  • 1970-01-01
  • 2019-05-17
  • 1970-01-01
  • 2012-08-16
  • 1970-01-01
相关资源
最近更新 更多