首页 > 解决方案 > 允许使用 Symfony 4 和 nginx 执行除 index.php 之外的其他 php 脚本

问题描述

我想我对语法的理解不够好,无法理解为什么我不能做到这一点。

给定以下文件夹结构

- www/website
-- public
--- index.php
--- otherscript.php

以及下面的 nginx.conf

server {
    listen          8000;
    server_name     localhost;
    root            /www/website/public;
    index           index.php;

    # optionally disable falling back to PHP script for the asset directories;
    # nginx will return a 404 error when files are not found instead of passing the
    # request to Symfony (improves performance but Symfony's 404 page is not displayed) 
    location / {
        # try to serve file directly, fallback to index.php
        try_files $uri /index.php$is_args$args;
    }

    # would always refer to index.php (server directive)
    location ~ \.php$ {
        ## tried this - no dice
        fastcgi_pass 127.0.0.1:9001;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        index $fastcgi_script_name;
    }

    location ~ ^/index\.php(/|$) {
        fastcgi_pass 127.0.0.1:9001;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        internal;
    }
}

我提出的每个请求都被重定向到 index.php,这是有道理的。我希望能够在不被重定向到 index.php 的情况下执行 localhost:8000/otherscript.php。

如何在不破坏 symfony 路由的情况下做到这一点?

标签: phpsymfonynginxnginx-location

解决方案


/index.php处理程序类似,您需要包含fastcgi_params文件,因此:

location ~ \.php$ {
    fastcgi_pass 127.0.0.1:9001;
    fastcgi_split_path_info ^(.+\.php)(/.*)$;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
    fastcgi_param DOCUMENT_ROOT $realpath_root;
}

一定要把它放在后面, location ~ ^/index\.php(/|$) {因为正则表达式的位置是按照配置中存在的顺序匹配的。


推荐阅读