For a client I want to do the following thing with .htaccess:

domainname.com/path must redirect to sub.domainname.com/path, but only if the first page is a deleted page / 404 page.

So all the existing pages must stay intact, and the deleted pages must redirect to a subdomain with the same path.

I used the following code on a Wordpress website, to only redirect 404 error pages to a new domain:

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

I have overwritten the following code in the existing htaccess file:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

It is not working. The problem is that now ALL pages are redirected to the new domain.

Only the 404's must be redirected.

What do I wrong?



As far I understand, .htaccess rewrite rules are executed before the request is proccesed by WordPress, or even by PHP engine, so you can not know if a URL will trigger a 404 error in .htaccess, you can not check if a given path will trigger a 404 at that level. You need to do it in WordPress itself:

// See https://developer.wordpress.org/reference/hooks/template_redirect/
add_action( 'template_redirect', 'cyb_redirect_not_found_paths' );
function cyb_redirect_not_found_paths() {

    // See https://developer.wordpress.org/reference/functions/is_404/
    if( is_404() ) {

        if( $_SERVER['REQUEST_URI'] == '/your_path' ) {

            $url_to = 'redirecton_rul';

            // See https://developer.wordpress.org/reference/functions/wp_redirect/
            wp_redirect( $url_to );



  • Thanks for your detailed answer. I have to add this code to the functions.php in the template folder right and have to change the 'redirecton_rul' in the code? I have tried it, with no succes. And what to fill at: == '/your_path'. Is it possibile to make the new path automatic the same on the new domain where it is redirected to? – Jurrt May 23 '17 at 11:24
  • Of course, $_SERVER['REQUEST_URI']' should contain the requested path, so you can append it to any domain of your choice. Please, nothe that your question include a generic "path" and so this answer is a generic approach. You can include the code in functions.php, but it is better to make it a plugin because this code has nothing to do with theming ("look and feel"). – cybmeta May 23 '17 at 11:30

Use this direction:

ErrorDocument 404 http://example.com/404/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.