我想将用户重定向到自定义 404 页面。
<IfModule mod_rewrite.c>
RewriteEngine On
# If the request is for a directory, do nothing
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# If the request is for an existing file, do nothing
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]
# Append ".php" extension to URLs without an extension
RewriteCond %{REQUEST_URI} !\.(html?|php)$
RewriteRule ^([^/]+)/$ $1.php
# Append ".php" extension to URLs with two path segments
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php
# If the request doesn't end with a slash or an extension, redirect to a trailing slash
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]
# Custom 404 error handling
ErrorDocument 404 /error
</IfModule>
这是我在 .htaccess 中配置的代码。 此代码仅适用于子目录,例如
https://example.com/about/abc
,但不适用于链接示例 https://example.com/abc
(仅显示错误消息“找不到文件。”)。
请告诉我应该怎样做才能使重定向适用于所有 404 页面。谢谢提前。
<IfModule mod_rewrite.c>
RewriteEngine On
# If the request is for a directory, do nothing
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# If the request is for an existing file, do nothing
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]
# Append ".php" extension to URLs without an extension
RewriteCond %{REQUEST_URI} !\.(html?|php)$
RewriteRule ^([^/]+)/$ $1.php
# Append ".php" extension to URLs with two path segments
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php
# If the request doesn't end with a slash or an extension, redirect to a trailing slash
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]
# Custom 404 error handling
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /error.php?request=$1 [L,QSA]
</IfModule>
使用 RewriteRule 指令添加了自定义 404 错误处理规则。此规则检查请求的文件或目录是否不存在(!-f 和 !-d)。如果满足此条件,则请求将被重写到 error.php 文件,并传递原始请求 URI 作为查询参数 (request=$1)
您需要在文档根目录中创建 error.php 文件来处理自定义 404 错误。
<?php
$request = $_GET['request'];
header('HTTP/1.1 404 Not Found');
echo "The requested URL '$request' was not found on this server.";