Explain Codes LogoExplain Codes Logo

How to redirect one HTML page to another on load

html
redirect
seo
user-experience
Nikita BarsukovbyNikita Barsukov·Aug 16, 2024
TLDR

To redirect instantly from one page to another, use the <meta> tag. Set http-equiv="refresh" and content="0;url=destination-url".

Example:

<meta http-equiv="refresh" content="0;url=https://www.example.com">

On page load, the visitor is immediately sent to https://www.example.com.

Old-school HTML redirection

Due to browsers compatibility and user's settings that may disable meta refresh, it is safer to include a fallback link.

<noscript> <meta http-equiv="refresh" content="0; URL='http://www.example.com'"/> <!-- Old is gold, but a simple link never gets old --> <a href="http://www.example.com">Redirect</a> </noscript>

JavaScript-disabled browsers will still respect the fallback link and take the redirect.

JavaScript redirection: Dynamic and programmable

When requiring more control or when conditions are to be inspected before redirection, JavaScript can change the location on the go.

window.location.href = "https://www.example.com";

If the time calls for a slower approach, add a delay:

setTimeout(function(){ window.location.href = "https://www.example.com"; // The delay that annoys us today, saves us tomorrow (from instant redirect troubles) }, 3000); // 3-second delay

Server-side redirection: For the SEO geeks

Search engine bots respect a 301 redirect. It transfers the search ranking of the old page to the new page, preserving the SEO juice.

Redirect 301 /oldpage.html /newpage.html

In the wor(l)d of WordPress, use plugins like Redirection to deal with redirects like a pro, without coding.

SEO and UX: Keeping Google and users happy

SEO and UX coexist in harmony when implementing redirects. Following Google's advice:

  1. HTTP status codes communicate the context to the search engines.
  2. Avoid redirect chains - not a fun party for the users or bots.
  3. rel="canonical" specifies the preferred version when there are similar content pages.
<link rel="canonical" href="http://www.example.com/newpage" />

Don't forget, performance is a ranking factor. Meta Refresh can be a tad slower than other methods.

Always have a Plan B: The manual fallback

In the unexpected event of a failed redirection, a manual fallback link to the rescue!

<noscript> <meta http-equiv="refresh" content="0; URL='http://www.newdestination.com'"/> <a href="http://www.newdestination.com">Click here if not redirected. Or just enjoy staying here!</a> </noscript>