.htaccess,将404错误重写到其他域

时间:2013-09-12 12:05:12

标签: apache .htaccess mod-rewrite

如何将所有404错误重定向到另一个域?

我找到了

Error 404 http://example.com/error.html

但我需要:

if Error 404 (.*) http://example.com/$1

我试过了:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ http://example.com/$1

但它会重定向所有请求,实际上如果我运行.php脚本生成一个包含404链接的页面,脚本的URL就会变为

http://example.com/script.php

相反,URL应该保持不变,只有404链接应该重定向到另一个域。

解决方案?

1 个答案:

答案 0 :(得分:6)

1 - 创建ErrorDocument指令,如下所示:

ErrorDocument 404 /404.php

2 - 然后像这样创建404.php

<?php
   if ($_SERVER["HTTP_HOST"] == "domain.com") // current domain
      header('Location: http://example.com' . $_SERVER["REQUEST_URI"], TRUE, 301);
?>

更新仅使用.htaccess:

RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^ http://example.com%{REQUEST_URI} [L,R=301]