.htaccess,将404错误重写到其他域
问题描述:
如何将所有404错误重定向到另一个域?
How can I redirect all the 404 errors to another domain?
我找到了
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会变成
But it redirects all the requests, in fact if I run a .php script which generate a page with some 404 links the URL of the script becomes
http://example.com/script.php
相反,URL应该保持不变,只有404链接应该重定向到另一个域.
Instead the URL should remains the same and just the 404 links should get redirected to the other domain.
解决方案?
答
1-创建ErrorDocument
指令,如下所示:
1 - Create ErrorDocument
directive like this:
ErrorDocument 404 /404.php
2-然后像这样创建您的404.php
:
2 - Then create your 404.php
like this:
<?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]