Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.htaccess, rewrite 404 errors to other domain

How can I redirect all the 404 errors to another domain?

I've found the

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

But I need:

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

I've tried:

RewriteEngine On

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

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

Instead the URL should remains the same and just the 404 links should get redirected to the other domain.

Solutions?

like image 401
Fez Vrasta Avatar asked Mar 23 '23 11:03

Fez Vrasta


1 Answers

1 - Create ErrorDocument directive like this:

ErrorDocument 404 /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);
?>

UPDATE Using just .htaccess:

RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^ http://example.com%{REQUEST_URI} [L,R=301]
like image 61
anubhava Avatar answered Apr 02 '23 20:04

anubhava