nginx + fpm 规则问题;找不到文件或脚本被下载而不是被执行

Posted

技术标签:

【中文标题】nginx + fpm 规则问题;找不到文件或脚本被下载而不是被执行【英文标题】:nginx + fpm rules problem; File not found or script is downloaded instead of being executed 【发布时间】:2020-02-24 13:38:24 【问题描述】:

我正在重构一个非常旧的应用程序,但我被困在 nginx 配置上;我所有的尝试都以下载而不是执行 php 脚本结束,或者以“找不到文件”结束

目录结构

public
│
└─── front
│   │   index.php
│   │   
│   │
│   └─── web_www.example.com
│       │   index.php
│       │   style.css
│       │   export/
            ...

目标

除了静态文件(.js.css...)之外的所有 URL 都必须路由到 public/front/index.php

例子:

http://www.example.com/ -> public/front/index.php http://www.example.com/index.php -> public/front/index.php https://www.example.com/mag/fr/contact.php -> public/front/index.php https://www.example.com/product-1.htm -> public/front/index.php https://www.example.com/style.css -> serve the file

为什么有些 URL 看起来像是要执行的 php 脚本? 因为它是一个以这种方式工作的旧应用程序;现在,只有 1 个前端控制器 (public/front/index.php) 负责执行代码

基础,不工作的虚拟主机

server 
    ...

    root /srv/app/public/front;
    index index.php;

    location / 
        try_files $uri $uri/ /index.php$is_args$args =404;
    

    location ~ \.php$ 
        fastcgi_pass unix:/var/run/php-fpm.app.sock;
        fastcgi_index index.php;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    

    location ~* \.(js|css|bmp|png|jpg|jpeg|gif|swf|ico)$ 
        try_files $uri =404;
    


    rewrite ^/(.*)$ /web_$http_host$uri break;

请问我做错了什么/错过了什么?

编辑 1

将尝试文件添加到该位置,就像@Florentin Stemate 建议的那样:

    location ~ \.php$ 
        try_files /index.php?$args $uri;
        ....
    

(我切换了顺序并把$uri放在最后,所以当url包含.php时,我们总是尝试通过前端控制器)

这样做对所有页面都有效,除了:

https://www.example.com/product-1.htm => 现在给出:

*2 内部重定向时重写或内部重定向循环 “/web_www.test-boutique.vm/web_www.test-boutique.vm/web_www.test-boutique.vm/web_www.test-boutique.vm/web_www.test-boutique.vm/.....”

【问题讨论】:

尝试在location ~ \.php$ 块中添加try_files $uri $uri/ /index.php?$args; 谢谢,https://www.example.com/mag/fr/contact.php 页面现在可以工作,但https://www.example.com/product-1.htm 仍然给出 404。 查看编辑了解详情; 如何将location ~* \.(js|css|bmp|png|jpg|jpeg|gif|swf|ico)$ 更改为location ~* \.(js|css|bmp|png|jpg|jpeg|gif|swf|ico|htm|html) 那么我认为您可以将location ~ \.php$ 更新为location ~ \.(php|htm)$ 这也应该向 index.php 发送对 htm 文件的请求 【参考方案1】:

您的try_files 语句中有错误。删除=404,使/index.php$is_args$args 成为最后一个参数。

例如:

location / 
    try_files $uri $uri/ /index.php$is_args$args;

try_files 语句的最后一个参数可以是 URI、状态码或命名位置。选一个!详情请见this document。

【讨论】:

我删除了它;但没有效果;

以上是关于nginx + fpm 规则问题;找不到文件或脚本被下载而不是被执行的主要内容,如果未能解决你的问题,请参考以下文章

配置Nginx和php-fpm用Sock套接字连接时,找不到php-fpm.sock的原因

PHP 文件上传到 NGINX & PHP5-FPM

nginx502问题

Nginx常见502错误

005_常见的502错误

nginx File not found 错误