【问题标题】:How do I get NGINX to properly rewrite and execute on a custom PHP application?如何让 NGINX 在自定义 PHP 应用程序上正确重写和执行?
【发布时间】:2017-07-28 15:56:39
【问题描述】:

我们有一个自定义的 PHP 应用程序,我们编写并在 Apache 上运行,使用 .htaccess 文件来处理 url 重写。我们正在尝试将其转换为在 NGINX 下使用 Plesk Onyx 下的 FPM 工作。

应用程序生成如下链接:

https://somedomain.com/mypage   (same as index/mypage)
https://somedomain.com/index/sitemap
https://somedomain.com/blog/some-article-name

这些 URL 映射到 index.php 文件,这些文件采用 request_uri 并使用它来呈现页面响应。

应用的结构嵌套如下:

docroot (/)

 ./index.php //handler for the request in /

 ./blog/index.php //handler for any request to /blog

每个 index.php 都希望收到一个 ?path={request_uri} 以便它可以将请求映射到控制器和操作。

我尝试了多种方法让 NGINX 使用 tryfiles 和重写来执行此操作,但没有运气。使用 rewrite 我可以让 / 工作,但它不会呈现 /mypage 或 /index/sitemap。

如果我尝试点击 /index/sitemap,它会下载 index.php 而不是执行它,如果我尝试访问博客,也会发生同样的事情。事实上,唯一有效的路径是 /,所有其他路径只是下载 index.php 文件。

这是我现在的配置,我哪里出错了?

location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
    expires 30d;
    add_header Pragma public;
    add_header Cache-Control “public”;
    try_files $uri @fallback;
}

location / {
    #index index.php index.html index.html;
    rewrite ^/([^?]*) /index.php?path=$1 break;
    rewrite ^blog/([^?]*) /blog/index.php?path=$1 break;
    #try_files $uri @fallback;

}    

【问题讨论】:

    标签: php nginx


    【解决方案1】:

    您的配置存在多个问题。我将忽略第一个 location 块,因为它似乎与您的问题无关。

    第一个 rewrite 将始终匹配,因此永远不会咨询第二个 rewrite。第二个rewrite 无论如何都不会匹配,因为nginx URI 总是以/ 开头。 [^?] 没有意义,因为 rewrite 使用不包括 ? 或查询字符串的规范化 URI。使用rewrite...break 意味着重写的URI 在同一位置处理,这是一个错误,因为该位置不具备处理PHP 文件的能力。请参阅this document 了解更多信息。

    使用try_files 的解决方案可能如下所示:

    location / {
        try_files $uri $uri/ /index.php?path=$uri&$args;
    }
    location /blog {
        try_files $uri $uri/ /blog/index.php?path=$uri&$args;
    }
    location ~ \.php$ { ... }
    

    请参阅this document 了解更多信息。

    【讨论】:

      猜你喜欢
      • 2023-02-22
      • 1970-01-01
      • 2014-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多