nginx 将所有 404 请求路由到 php 脚本

nginx 将所有 404 请求路由到 php 脚本

我想将所有 404 请求路由到 php 脚本,我该怎么做?我的 nginx 配置是:

server {
    listen 81;
    listen [::]:81;
    root /srv/http/paste.lan/www;
    autoindex on;
    client_max_body_size 20M;
    index index.txt index.html index.htm index.php;
    server_name paste.lan;
    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
    }

    # pass PHP scripts to FastCGI server
    #
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
    #
    #   # With php-fpm (or other unix sockets):
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
    #   # With php-cgi (or other tcp sockets):
    #   fastcgi_pass 127.0.0.1:9000;
    }


    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
        deny all;
    }
}

我尝试过的事情:

尝试#1:

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ /index.php;
    }
  • 这仅适用于不以 .php 结尾的 URI,例如/DoesNotExist.ph传递给 index.php ,但/DoesNotExist.php获取标准 nginx 404 页面。

尝试#2:

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
    }
    error_page 404 /index.php;

这种方法有效,所有 404 请求都会传递到 index.php这会强制响应代码为 404,即使 index.php 包含:

<?php
http_response_code(200);
die("index.php");

它仍将提供响应代码 404 :(

尝试#3:

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
    }
    error_page 404 =200 /index.php;

这也算是可行的,所有 404 请求都传递给 index.php这会强制响应代码为 200,即使 index.php 包含:

<?php
http_response_code(400);// HTTP 400 Bad Request
die("index.php");

它仍将被视为 HTTP 200 OK :(

答案1

error_page指令包含将响应代码更改为另一个的选项。

手册页

如果错误响应由代理服务器或 FastCGI/uwsgi/SCGI/gRPC 服务器处理,并且服务器可能返回不同的响应代码(例如 200、302、401 或 404),则可以使用其返回的代码进行响应:

错误页面 404 = /404.php;

你应该使用:

error_page 404 = /index.php;

相关内容