15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started
01.11.2024

How to Redirect a 404 Error: Complete Guide for Apache, Nginx & PHP

A 404 error is one of the most common — and most damaging — issues a website can face. When a visitor lands on a page that no longer exists, they're met with a dead end. That broken experience drives users away, increases bounce rates, and quietly erodes your search engine rankings over time.

The good news? With the right redirect strategy, you can intercept those 404 errors, guide users to relevant content, and protect both your traffic and your SEO. This comprehensive guide covers every major method for redirecting 404 errors, including Apache's .htaccess, Nginx server blocks, and PHP-based solutions — with real configuration examples you can implement today.

What Is a 404 Error and Why Does It Matter?

A 404 Not Found error is an HTTP status code returned by a server when it cannot locate the requested resource. This happens for several reasons:

  • A page was deleted or moved without a redirect in place
  • A user followed a broken or outdated external link
  • A URL was mistyped or restructured during a site migration
  • Internal links were not updated after content changes

From a user experience perspective, hitting a 404 page is frustrating. From an SEO perspective, it signals to search engines that your site has structural problems. Crawl budget gets wasted, link equity is lost, and rankings can suffer — especially if high-authority backlinks point to dead URLs.

Implementing proper 404 redirects is not optional maintenance. It is a core part of running a healthy, well-optimized website.

Method 1: Redirecting 404 Errors Using .htaccess (Apache Servers)

If your website is hosted on an Apache web server, the .htaccess file is your primary tool for managing redirects at the server level. This method is fast, reliable, and requires no programming knowledge.

Step 1: Locate or Create the .htaccess File

The .htaccess file lives in your website's root directory (typically public_html/ or www/). If it doesn't exist yet, create a new plain text file and name it exactly .htaccess — including the leading dot.

> Tip: If you're managing your hosting environment through a control panel, you can find and edit this file directly in the file manager. Users on a VPS with cPanel can access it through the built-in File Manager under cPanel's interface.

Step 2: Set a Custom 404 Error Document

Add the following line to your .htaccess file to serve a custom HTML page whenever a 404 error occurs:

ErrorDocument 404 /custom-404-page.html

Replace /custom-404-page.html with the actual path to your custom error page. This tells Apache to serve that page instead of the default server error response.

Step 3: Redirect All 404 Errors to a Specific URL

If you want to redirect users to a working page — rather than just showing a custom error — use Apache's mod_rewrite module:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ https://yourdomain.com/new-page [R=301,L]

What this does:

    RewriteEngine On — activates the rewrite engine
    RewriteCond %{REQUEST_FILENAME} !-f — checks that the requested file does not physically exist
    RewriteRule ^(.*)$ https://yourdomain.com/new-page [R=301,L] — redirects all non-existent file requests to your chosen URL with a permanent (301) redirect
    
    > Important: Always use 301 redirects (permanent) rather than 302 (temporary) when redirecting broken URLs. A 301 passes link equity to the destination page and tells search engines the move is permanent.
    Step 4: Redirect Specific Dead URLs
    For surgical precision — redirecting individual broken URLs rather than all 404s — add specific redirect rules:
    Redirect 301 /old-page https://yourdomain.com/new-page
    Redirect 301 /deleted-article https://yourdomain.com/related-article
    This approach is ideal after a site migration or when restructuring your URL hierarchy.
    Method 2: Configuring 404 Redirects in Nginx
    If your server runs Nginx, redirect configuration is handled inside the server block of your site's configuration file rather than in a .htaccess file.
    Step 1: Open the Nginx Configuration File
    Nginx configuration files are typically located at:
    
    /etc/nginx/sites-available/yourdomain.conf
  • /etc/nginx/conf.d/yourdomain.conf

Open the relevant file with a text editor:

sudo nano /etc/nginx/sites-available/yourdomain.conf

Step 2: Set a Custom 404 Error Page

Inside your server {} block, add the following directive:

error_page 404 /custom-404-page.html;

This instructs Nginx to serve your custom HTML page whenever a 404 error is triggered.

Step 3: Redirect 404 Errors to Another URL

To redirect users to a working page when a 404 occurs, use Nginx's named location feature:

server {
    listen 80;
    server_name yourdomain.com;

    location / {
        try_files $uri $uri/ @custom_redirect;
    }

    location @custom_redirect {
        return 301 https://yourdomain.com/new-page;
    }
}

How this works:

  • try_files $uri $uri/ — Nginx first tries to serve the requested file or directory
  • If neither exists, it falls through to the @custom_redirect named location
  • The named location issues a 301 redirect to your specified destination URL

Step 4: Test and Reload Nginx

After editing the configuration, always test for syntax errors before reloading:

sudo nginx -t

If the test passes with syntax is ok, reload Nginx to apply your changes:

sudo systemctl reload nginx

Never skip the syntax test — a misconfigured Nginx file can take your entire site offline.

> Note: Managing Nginx configurations is straightforward when you have full root access to your server. AlexHost's VPS Hosting and Dedicated Servers give you complete control over your server environment, making configurations like these quick and painless.

Method 3: Handling 404 Redirects with PHP

For sites running PHP, you can handle 404 redirects programmatically using a custom PHP error page. This method offers the most flexibility — you can log errors, display dynamic content, or apply conditional redirect logic.

Step 1: Create a Custom 404 PHP File

Create a file named 404.php in your root directory with the following content:

<?php
// Send a 301 permanent redirect header
header("HTTP/1.1 301 Moved Permanently");
header("Location: /new-page.php");
exit();
?>

For a more user-friendly approach that shows a helpful page instead of immediately redirecting:

<?php
http_response_code(404);
// Log the 404 for monitoring
error_log("404 Error: " . $_SERVER['REQUEST_URI']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Page Not Found</title>
</head>
<body>
    <h1>Oops! Page Not Found</h1>
    <p>The page you're looking for doesn't exist. <a href="/">Return to Homepage</a></p>
</body>
</html>

Step 2: Point Your Server to the Custom PHP File

For Apache, add to your .htaccess:

ErrorDocument 404 /404.php

For Nginx, add to your server block:

error_page 404 /404.php;

location = /404.php {
    internal;
}

The internal directive ensures the error page can only be accessed internally by Nginx — not directly by users typing the URL.

Method 4: WordPress-Specific 404 Redirect Solutions

If your site runs on WordPress, you have additional options beyond server-level configuration.

Using a Plugin

Plugins like Redirection, Rank Math SEO, or Yoast SEO include built-in 404 monitoring and redirect management. These tools let you:

  • View all 404 errors in a dashboard
  • Set up redirects without touching server files
  • Automatically suggest redirects based on similar existing URLs

Editing functions.php

For developers, you can add redirect logic directly to your theme's functions.php:

function custom_404_redirect() {
    if ( is_404() ) {
        wp_redirect( home_url(), 301 );
        exit();
    }
}
add_action( 'template_redirect', 'custom_404_redirect' );

This redirects all 404 errors to the homepage with a 301 status.

Testing Your 404 Redirects

After implementing any redirect method, thorough testing is essential. Here's how to verify everything works correctly:

Manual Browser Testing

  1. Navigate to a URL on your site that you know doesn't exist (e.g., https://yourdomain.com/this-page-does-not-exist)
  2. Confirm you are redirected to the correct destination
  3. Check the browser's address bar to ensure the URL has updated

Using curl for HTTP Status Verification

curl -I https://yourdomain.com/non-existent-page

Look for HTTP/1.1 301 Moved Permanently in the response headers, followed by the Location: header pointing to your destination URL.

Online Tools

Use tools like:

  • Google Search Console — identifies 404 errors Google has encountered while crawling your site
  • Screaming Frog SEO Spider — crawls your site and flags broken links
  • Redirect Checker (redirect-checker.org) — verifies redirect chains and final destinations

Best Practices for Managing 404 Errors

1. Design a Helpful Custom 404 Page

Even when you redirect most 404 errors, some will inevitably slip through. A well-designed custom 404 page should include:

  • A clear, friendly message explaining the page wasn't found
  • A search bar so users can find what they're looking for
  • Links to your most popular pages or categories
  • Your site's main navigation menu
  • A link back to the homepage

2. Use 301 Redirects — Not 302

Always use 301 (permanent) redirects for dead pages. A 302 (temporary) redirect does not pass SEO value and tells search engines the original URL may return. Use 302 only when a page is genuinely temporarily unavailable.

3. Avoid Redirect Chains

A redirect chain occurs when URL A redirects to URL B, which redirects to URL C. Each hop in the chain dilutes link equity and slows page load times. Always redirect directly to the final destination URL.

4. Monitor 404 Errors Continuously

404 errors are not a one-time fix. New broken links appear constantly — from external sites changing their URLs, from your own content updates, and from user typos. Set up ongoing monitoring with:

  • Google Search Console (Coverage report)
  • Ahrefs or SEMrush site audit tools
  • Server access log analysis

5. Prioritize High-Value 404 Pages

Not all 404 errors are equally important. Focus first on pages that:

  • Have backlinks from other websites (check with Ahrefs or Moz)
  • Receive significant organic search traffic (visible in Google Search Console)
  • Are linked internally from other pages on your site

6. Keep SSL Active

A 404 redirect on an HTTPS site requires a valid SSL certificate. If your certificate has expired, users will encounter a security warning before they even see your redirect. Ensure your SSL is always current — AlexHost offers SSL Certificates to keep your site secure and trusted by both users and search engines.

404 Errors and SEO: What You Need to Know

Understanding how 404 errors affect your SEO helps you prioritize fixes correctly.

Do 404 Errors Directly Hurt Rankings?

A single 404 error on a low-traffic, unlinked page will not meaningfully harm your rankings. However, widespread 404 errors — especially on pages with backlinks or significant internal link equity — can:

  • Waste crawl budget, causing Google to crawl fewer of your important pages
  • Result in lost link equity from external backlinks pointing to dead URLs
  • Increase bounce rate signals if users frequently land on error pages
  • Cause indexed pages to be removed from Google's index over time

Soft 404s Are Worse Than Hard 404s

A soft 404 occurs when a page returns a 200 OK status code but displays a "page not found" message. This is more damaging than a proper 404 because search engines may index the empty or unhelpful page. Always ensure your error pages return the correct HTTP status code.

When you identify 404 pages with backlinks, redirecting them to the most relevant live page is one of the highest-ROI SEO tasks you can perform. You're essentially reclaiming link equity that was previously being lost.

Choosing the Right Hosting Environment for Reliable Redirect Management

Your ability to implement and manage 404 redirects effectively depends heavily on your hosting environment. Shared hosting plans may restrict access to server configuration files or limit .htaccess capabilities.

For full control over your server configuration — including custom Nginx setups, PHP configurations, and unrestricted .htaccess access — consider upgrading to a more capable hosting solution:

  • VPS Hosting — Full root access, choose your OS, configure Apache or Nginx exactly as needed
  • Dedicated Servers — Maximum performance and complete server control for high-traffic sites
  • Shared Web Hosting — Ideal for smaller sites with standard .htaccess redirect needs
  • VPS Control Panels — Manage server configurations through an intuitive GUI without command-line expertise

Having the right infrastructure in place means redirect rules are applied instantly, server reloads are smooth, and you're never blocked by hosting restrictions when fixing critical site issues.

Conclusion

Redirecting 404 errors is not just a technical housekeeping task — it is a fundamental part of maintaining a high-performing, user-friendly, and SEO-optimized website. Every broken link is a potential lost visitor, a wasted backlink, and a negative signal to search engines.

By implementing the methods covered in this guide — whether through Apache's .htaccess, Nginx server block configuration, or PHP-based redirect scripts — you can systematically eliminate dead ends on your site and guide both users and search engine crawlers to the right content.

Key takeaways:

  • Use 301 redirects for permanently moved or deleted pages
  • Configure redirects at the server level (Apache or Nginx) for best performance
  • Test every redirect with browser checks and HTTP header inspection tools
  • Monitor continuously with Google Search Console and SEO audit tools
  • Design a helpful custom 404 page as a safety net for any errors that slip through
  • Prioritize redirecting 404 pages with backlinks for maximum SEO recovery

Start with your highest-traffic and most-linked broken pages, then build a systematic process for catching new 404 errors as they appear. Your users — and your search rankings — will thank you.

15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started