.htaccess 重定向404错误htaccess后重写URL

.htaccess 重定向404错误htaccess后重写URL,.htaccess,redirect,url-rewriting,rewrite,custom-error-pages,.htaccess,Redirect,Url Rewriting,Rewrite,Custom Error Pages,所以我知道这可能看起来有点奇怪,但为了一致性,我希望我的所有URL都以这种形式显示:到目前为止,我已经让常规页面正常工作,但我似乎无法让错误页面正常工作 如果用户访问的页面或目录不存在,我希望浏览器硬重定向到:但是,该目录实际上不存在。错误页面的实际位置将位于/pages/errors/404.php下 此外,虽然我不需要所有各种错误(400、401、403、404、500)的确切答案,但我将应用给定的任何方法将所有这些重定向到它们的“正确”URL(例如,等等) 有什么想法吗?在.htacces

所以我知道这可能看起来有点奇怪,但为了一致性,我希望我的所有URL都以这种形式显示:到目前为止,我已经让常规页面正常工作,但我似乎无法让错误页面正常工作

如果用户访问的页面或目录不存在,我希望浏览器硬重定向到:但是,该目录实际上不存在。错误页面的实际位置将位于/pages/errors/404.php下

此外,虽然我不需要所有各种错误(400、401、403、404、500)的确切答案,但我将应用给定的任何方法将所有这些重定向到它们的“正确”URL(例如,等等)


有什么想法吗?

在.htaccess文件中,如果您使用的是apache,您可以尝试使用

错误规则第404页
ErrorDocument 404

请在.htaccess中尝试以下操作:

RewriteEngine On
RewriteRule ^404/?$ /pages/errors/404.php [L]
.htaccess

ErrorDocument 404 http://example.com/404/
ErrorDocument 500 http://example.com/500/
# or map them to one error document:
# ErrorDocument 404 /pages/errors/error_redirect.php
# ErrorDocument 500 /pages/errors/error_redirect.php

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} ^/404/$
RewriteRule ^(.*)$ /pages/errors/404.php [L]

RewriteCond %{REQUEST_URI} ^/500/$
RewriteRule ^(.*)$ /pages/errors/500.php [L]

# or map them to one error document:
#RewriteCond %{REQUEST_URI} ^/404/$ [OR]
#RewriteCond %{REQUEST_URI} ^/500/$
#RewriteRule ^(.*)$ /pages/errors/error_redirect.php [L]
ErrorDocument
将所有404重定向到一个特定的URL,将所有500重定向到另一个URL(替换为您的域)

重写规则将该URL映射到实际的404.php脚本。如果需要的话,RewriteCond正则表达式可以变得更通用,但我认为必须显式定义所有要重写的ErrorDocument代码

本地重定向:

将.htaccess ErrorDocument更改为存在的文件(必须存在,否则将出现错误):

404_redirect.php

<?php
   header('Location: /404/');
   exit;
?>
<?php
   $error_url = $_SERVER["REDIRECT_STATUS"] . '/';
   $error_path = $error_url . '.php';

   if ( ! file_exists($error_path)) {
      // this is the default error if a specific error page is not found
      $error_url = '404/';
   }

   header('Location: ' . $error_url);
   exit;
?>

尝试将此规则添加到htaccess的顶部:

RewriteEngine On
RewriteRule ^404/?$ /pages/errors/404.php [L]
然后根据该(或您拥有的任何其他规则):


将此代码放入.htaccess文件中

RewriteEngine On
ErrorDocument 404 /404.php

其中
404.php
文件名
,并且位于根目录下。你可以把
完整路径
放在这里。

正是我要找的。。。但是在ErrorDocument声明中是否还需要使用相对路径?如果使用相对路径,则需要指向现有文件,然后该文件可以重定向到不存在的/404/url。现在编辑我的答案来显示这一点…我能有一个文件重定向任何错误吗?通过使用url查询或其他什么?@LeinardoSmtih-I再次更新以显示更多示例。希望有帮助!谢谢你的回答,但就我所知,这对401和500等其他错误表单不起作用…它起作用,但我有一个问题,如果我使用,那么我将获得404页面内容,但URL没有更改。我的意思是,我得到了404页,但网址仍然显示。应该是。正确的?
RewriteEngine On
ErrorDocument 404 /404.php