Logo

How to redirect one HTML page to another on load?

There are multiple ways to redirect an HTML page to another page automatically. Here are the most common methods:

1. Meta Refresh Tag

Use a <meta> tag in the document’s <head> to redirect after a specified time (0 seconds for immediate redirect):

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <!-- Redirect immediately --> <meta http-equiv="refresh" content="0; url=https://example.com" /> <title>Redirecting...</title> </head> <body> If you are not redirected, <a href="https://example.com">click here</a>. </body> </html>
  • Pros: Easy to set up; no JavaScript needed.
  • Cons: Not ideal for SEO; some older browsers or screen readers might handle meta refresh differently.

2. JavaScript Redirect

Place a small script in the <head> or at the bottom of the <body> to redirect when the page loads:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Redirecting...</title> <script> // Redirect immediately on page load window.location.replace("https://example.com"); // OR: window.location.href = "https://example.com"; </script> </head> <body> If you are not redirected, <a href="https://example.com">click here</a>. </body> </html>
  • window.location.replace() doesn’t leave an entry in the browser’s history, whereas window.location.href does.
  • Pros: More control over timing and conditions; can show a message or spinner before redirecting.
  • Cons: Requires JavaScript enabled; not suitable if users/bots might have JS disabled.

3. Server-Side Redirect (Preferred for SEO)

If you control the server, you can set an HTTP 301 (Moved Permanently) or 302 (Found) status code with the Location header. This is often done in server-side code or server configurations (e.g., Apache .htaccess, Nginx configs, etc.). For instance, a simple PHP example:

<?php header('Location: https://example.com', true, 301); exit; ?>
  • Pros: Ideal for SEO; search engines and browsers see the correct HTTP status code.
  • Cons: Requires server-side access, not just static HTML hosting.

Best Practices

  1. Use Meta Refresh or JavaScript for quick prototypes or static-hosted pages where you can’t configure the server.
  2. Use Server-Side Redirects wherever possible for proper SEO handling and clean user experience.
  3. Give Fallback: Provide a link in case the automatic redirect fails or JavaScript is disabled.

Strengthen Your Web Development Skills

If you’re interested in solidifying your foundation in JavaScript (which is often used for redirects and web app logic), consider these courses on DesignGurus.io:

By mastering JavaScript and understanding best practices for redirects, you’ll create more user-friendly, SEO-compliant websites. Additionally, visit the DesignGurus.io YouTube channel for free tutorials on coding best practices and system design.

CONTRIBUTOR
TechGrind