我想将所有 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 :(