dxszzcylm 发表于 2012-5-22 00:25:57

How to EASILY 301 redirect all 404 error pages to root domain using WordPress

Alright so a few days ago I successfully purchased an expiring domain from an auction site, and after wasting a few hours doing 301 redirects manually (monitoring 404s and adding redirects by hand in .htaccess file) I accidently found this super easy method to 301 redirect all 404 error pages to root domain.

This trick was simply done by a WP core function called wp_redirect(). Here are the parameters for the function:$location
(string) (required) The absolute URI which the user will be redirected to.
Default: None

$status
(integer) (optional) The status code to use.
Default: 302Here's how the function should be used:<?php
wp_redirect( $location, $status );
exit;
?>
Here's a real life example<?php wp_redirect( get_option( 'siteurl' ); exit; ?>
What this does is, calling the get_option('siteurl') will basically return the default domain name that you're using (One that you've set in the Settings > General tab). And then, redirects it using a 302 since we haven't exclusively specified that we need a 301 redirect (302 is the default).But.. this isn't what we want, we need it to redirect with a 301, right?<?php wp_redirect(get_option('siteurl'),301); ?>
Yep, right there. This basically gets the default domain name and makes the redirect with a 301.So how to redirect all error pages to default domain name (root domain) with a 301?

Simple, create a file and name it 404.php and paste the above code in it, then replace your existing 404.php with it.

Remember that you need to replace the 404.php in your theme folder, which is located at wp-content > themes > your theme.

Enjoy~
页: [1]
查看完整版本: How to EASILY 301 redirect all 404 error pages to root domain using WordPress