如何让 Nginx 将对不存在的文件的所有请求重定向到单个 php 文件?

Ric*_*ard 8 php nginx redirect php-fpm

我有以下 nginx vhost 配置:

server {
    listen 80 default_server;

    access_log /path/to/site/dir/logs/access.log;
    error_log /path/to/site/dir/logs/error.log;

    root /path/to/site/dir/webroot;
    index index.php index.html;

    try_files $uri /index.php;

    location ~ \.php$ {
            if (!-f $request_filename) {
                    return 404;
            }

            fastcgi_pass localhost:9000;
            fastcgi_param SCRIPT_FILENAME /path/to/site/dir/webroot$fastcgi_script_name;
            include /path/to/nginx/conf/fastcgi_params;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想重定向所有与 index.php 存在的文件不匹配的请求。这适用于目前大多数 URI,例如:

example.com/asd
example.com/asd/123/1.txt
Run Code Online (Sandbox Code Playgroud)

无论是中asdasd/123/1.txt存在,所以他们重定向到的index.php和工作正常。但是,如果我输入 url example.com/asd.php,它会尝试查找asd.php,当找不到时,它会返回 404 而不是将请求发送到index.php

有没有得到一个方式asd.php进行也发送到index.php如果asd.php不存在?

Mar*_*ald 12

根据您的其他评论,这听起来可能是最佳方式,尽管它不是一个漂亮的配置。

server {
    listen 80 default_server;

    access_log /path/to/site/dir/logs/access.log;
    error_log /path/to/site/dir/logs/error.log;

    root /path/to/site/dir/webroot;
    index index.php index.html;

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

    location ~ \.php$ {
        try_files $uri @missing;

        fastcgi_pass localhost:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include /path/to/nginx/conf/fastcgi_params;
    }

    location @missing {
        rewrite ^ /error/404 break;

        fastcgi_pass localhost:9000;
        fastcgi_param SCRIPT_FILENAME $document_root/index.php;
        include /path/to/nginx/conf/fastcgi_params;
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 6

哇,我想你想要替换的代码是:

error_page 404 /index.php
Run Code Online (Sandbox Code Playgroud)

...如果我正确阅读了您想要的内容。