How can I redirect 404 (bad url) to the homepage?

Member

by pietro , in category: SEO , a year ago

How can I redirect 404 (bad url) to the homepage?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

2 answers

Member

by zion , a year ago

@pietro 

To redirect a 404 error page to the homepage, you can use a .htaccess file on an Apache web server or modify the web.config file on an IIS server. Here's how to do it:


Apache web server:

  1. Create or edit your .htaccess file in the root directory of your website.
  2. Add the following line of code at the end of the file:ErrorDocument 404 /index.phpThis assumes that your homepage is called index.php. If your homepage has a different name, replace "index.php" with the appropriate filename.
  3. Save the changes to your .htaccess file and upload it to your web server.


IIS web server:

  1. Open the web.config file in the root directory of your website.
  2. Add the following code within the <system.webServer> tags:<httpErrors errorMode="Custom"> <remove statusCode="404" subStatusCode="-1" /> <error statusCode="404" prefixLanguageFilePath="" path="/" responseMode="Redirect" /> </httpErrors>
  3. Save the changes to your web.config file and upload it to your web server.


With either of these methods, when a user tries to access a page that doesn't exist on your website, they will automatically be redirected to your homepage.

by dejuan.watsica , 2 months ago

@pietro 

In addition to the above methods, you can also perform the redirection within your website's code. Here's how you can do it in PHP:

  1. Create or open the .htaccess file in the root directory of your website.
  2. Add the following lines of code to the file:
1
2
3
4
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]


  1. Save the changes to the .htaccess file and upload it to your web server.
  2. Open your index.php file (or any other file you want to use as the homepage).
  3. Add the following PHP code at the top of the file:
1
2
3
4
5
6
<?php
if ($_SERVER['REQUEST_URI'] == '/404-page-url') {
    header("Location: /");
    exit();
}
?>


Be sure to replace "/404-page-url" with the actual URL of your 404 page. This code checks if the current page being accessed is the 404 error page and redirects the user to the homepage using the header() function.


Save the changes to the file, and the next time someone tries to access a non-existing page on your website, they will be redirected to the homepage.