Redirect from an HTML page

Questions : Redirect from an HTML page

Is it possible to set up a basic HTML page to redirect to another page on load?

Total Answers: 25 Answers 25


Popular Answers:

  1. Try using:

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

    Note: Place it in the <head> section.

    Additionally for older browsers if you add a quick link in case it doesn’t refresh correctly:

    <p><a href="http://example.com/">Redirect</a></p>

    Will appear as

    Redirect

    This will still allow you to get to where you’re going with an additional click.

  2. JavaScript

    <script type="text/javascript"> window.location.href = "http://example.com"; </script> 

    Meta tag

    <meta http-equiv="refresh" content="0;url=http://example.com"> 
  3. This is a sum up of every previous answers plus an additional solution using HTTP Refresh Header via .htaccess

    1. HTTP Refresh Header

    First of all, you can use .htaccess to set a refresh header like this

    Header set Refresh "3" 

    This is the “static” equivalent of using the header() function in PHP

    header("refresh: 3;"); 

    Note that this solution is not supported by every browser.

    2. JavaScript

    With an alternate URL:

    <script> setTimeout(function(){location.href="http://example.com/alternate_url.html"} , 3000); </script> 

    Without an alternate URL:

    <script> setTimeout("location.reload(true);",timeoutPeriod); </script> 

    Via jQuery:

    <script> window.location.reload(true); </script> 

    3. Meta Refresh

    You can use meta refresh when dependencies on JavaScript and redirect headers are unwanted

    With an alternate URL:

    <meta http-equiv="Refresh" content="3; url=http://example.com/alternate_url.html"> 

    Without an alternate URL:

    <meta http-equiv="Refresh" content="3"> 

    Using <noscript>:

    <noscript> <meta http-equiv="refresh" content="3" /> </noscript> 

    Optionally

    As recommended by Billy Moon, you can provide a refresh link in case something goes wrong:

    If you are not redirected automatically: <a href='http://example.com/alternat_url.html'>Click here</a>

    Resources

  4. If you are looking forward to follow modern web standards, you should avoid plain HTML meta redirects. If you can not create server-side code, you should choose JavaScript redirect instead.

    To support JavaScript-disabled browsers add a HTML meta redirect line to a noscript element. The noscript nested meta redirect combined with the canonical tag will help your search engine rankings as well.

    If you would like to avoid redirect loops, you should use the location.replace() JavaScript function.

    A proper client-side URL redirect code looks like this (with an Internet Explorer 8 and lower fix and without delay):

    <!-- Pleace this snippet right after opening the head tag to make it work properly --> <!-- This code is licensed under GNU GPL v3 --> <!-- You are allowed to freely copy, distribute and use this code, but removing author credit is strictly prohibited --> <!-- Generated by http://insider.zone/tools/client-side-url-redirect-generator/ --> <!-- REDIRECTING STARTS --> <link rel="canonical" href="https://stackoverflow.com/"/> <noscript> <meta http-equiv="refresh" content="0; URL=https://stackoverflow.com/"> </noscript> <!--[if lt IE 9]><script type="text/javascript">var IE_fix=true;</script><![endif]--> <script type="text/javascript"> var url = "https://stackoverflow.com/"; if(typeof IE_fix != "undefined") // IE8 and lower fix to pass the http referer { document.write("redirecting..."); // Don't remove this line or appendChild() will fail because it is called before document.onload to make the redirect as fast as possible. Nobody will see this text, it is only a tech fix. var referLink = document.createElement("a"); referLink.href = url; document.body.appendChild(referLink); referLink.click(); } else { window.location.replace(url); } // All other browsers </script> <!-- Credit goes to http://insider.zone/ --> <!-- REDIRECTING ENDS --> 
  5. The following meta tag, placed between inside the head, will tell the browser to redirect:

    <meta http-equiv="Refresh" content="seconds; url=URL"> 

    Replace seconds with the number of seconds to wait before it redirects, and replace URL with the URL you want it to redirect to.

    Alternatively, you can redirect with JavaScript. Place this inside of a script tag anywhere on the page:

    window.location = "URL" 
  6. It would be better to set up a 301 redirect. See the Google’s Webmaster Tools article 301 redirects.

  7. You could use a META “redirect”:

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

    or JavaScript redirect (note that not all users have JavaScript enabled so always prepare a backup solution for them)

    <script language="javascript"> window.location = "http://new.example.com/address"; </script> 

    But I’d rather recommend using mod_rewrite, if you have the option.

  8. As soon as the page loads, the init function is fired and the page is redirected:

    <!DOCTYPE html> <html> <head> <title>Example</title> <script> function init() { window.location.href = "www.wherever.com"; } </script> </head> <body onload="init()"> </body> </html> 
  9. Place the following code between the <HEAD> and </HEAD> tags of your HTML code:

    <meta HTTP-EQUIV="REFRESH" content="0; url=http://example.com/index.html"> 

    The above HTML redirect code will redirect your visitors to another web page instantly. The content="0; may be changed to the number of seconds you want the browser to wait before redirecting.

  10. Put the following code in the <head> section:

    <meta http-equiv="refresh" content="0; url=http://address/"> 
  11. I found a problem while working with a jQuery Mobile application, where in some cases my Meta header tag wouldn’t achieve a redirection properly (jQuery Mobile doesn’t read headers automatically for each page so putting JavaScript there is also ineffective unless wrapping it in complexity). I found the easiest solution in this case was to put the JavaScript redirection directly into the body of the document, as follows:

    <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="refresh" content="0;url=myURL" /> </head> <body> <p>You are not logged in!</p> <script language="javascript"> window.location = "myURL"; </script> </body> </html> 

    This seems to work in every case for me.

  12. The simple way which works for all types of pages is just to add a meta tag in the head:

    <html> <head> ... <meta HTTP-EQUIV="REFRESH" content="seconds; url=your.full.url/path/filename"> ... </head> <body> Don't put much content, just some text and an anchor. Actually, you will be redirected in N seconds (as specified in content attribute). That's all. ... </body> </html> 
  13. You can auto redirect by HTTP Status Code 301 or 302.

    For PHP:

    <?php Header("HTTP/1.1 301 Moved Permanently"); Header("Location: http://www.redirect-url.com"); ?> 
  14. I use a script which redirects the user from index.html to relative url of Login Page

    <html> <head> <title>index.html</title> </head> <body onload="document.getElementById('lnkhome').click();"> <a href="/Pages/Login.aspx" id="lnkhome">Go to Login Page</a> </body> </html> 
  15. You should use JavaScript. Place the following code in your head tags:

    <script type="text/javascript"> window.location.assign("http://www.example.com") </script> 
  16. <body onload="window.location = 'http://example.com/'">
  17. Razor engine for a 5 second delay:

    <meta http-equiv="Refresh" content="5; [email protected]("Search", "Home", new { id = @Model.UniqueKey }))"> 
  18. <?php header("Location: http://example.com", true, 302); exit; ?>
  19. As far as I understand them, all the methods I have seen so far for this question seem to add the old location to the history. To redirect the page, but do not have the old location in the history, I use the replace method:

    <script> window.location.replace("http://example.com"); </script> 
  20. You don’t need any JavaScript code for this. Write this in the <head> section of the HTML page:

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

    As soon as the page loads at 0 seconds, you can go to your page.

  21. This is a redirect solution with everything I wanted, but I could not find in a nice clean snippet to cut & paste.

    This snippet has a number of advantages:

    • lets you catch and retain any querystring parameters folks have on their URL
    • makes the link unique to avoid unwanted caching
    • lets you inform users of the old and new site names
    • shows a settable countdown
    • can be used for deep-link redirects as retains parameters

    How to use:

    If you migrated an entire site then on the old server stop the original site and create another with this file as the default index.html file in the root folder. Edit the site settings so that any 404 error is redirected to this index.html page. This catches anyone who accesses the old site with a link into a sub-level page etc.

    Now go to the opening script tag and edit the oldsite and newSite web addresses, and change the seconds value as needed.

    Save and start your website. Job done – time for a coffee.

    <!DOCTYPE html> <html> <head> <META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE"> <META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE"> <META HTTP-EQUIV="EXPIRES" CONTENT="Mon, 22 Jul 2002 11:12:01 GMT"> <style> body { margin: 200px; font: 12pt helvetica; } </style> </head> <body> </body> <script type="text/javascript"> // Edit these to suit your needs. var oldsite = 'http://theoldsitename.com' var newSite = "https://thenewsitename.com"; var seconds = 20; // countdown delay. var path = location.pathname; var srch = location.search; var uniq = Math.floor((Math.random() * 10000) + 1); var newPath = newSite + path + (srch === '' ? "?" + uniq : srch + "&" + uniq); document.write ('<p>As part of hosting improvements, the system has been migrated from ' + oldsite + ' to</p>'); document.write ('<p><a href="' + newPath + '">' + newSite + '</a></p>'); document.write ('<p>Please take note of the new website address.</p>'); document.write ('<p>If you are not automatically redirected please click the link above to proceed.</p>'); document.write ('<p id="dvCountDown">You will be redirected after <span id = "lblCount"></span>&nbsp;seconds.</p>'); function DelayRedirect() { var dvCountDown = document.getElementById("dvCountDown"); var lblCount = document.getElementById("lblCount"); dvCountDown.style.display = "block"; lblCount.innerHTML = seconds; setInterval(function () { seconds--; lblCount.innerHTML = seconds; if (seconds == 0) { dvCountDown.style.display = "none"; window.location = newPath; } }, 1000); } DelayRedirect() </script> </html>

  22. You can do it in JavaScript:

    location = "url"; 
  23. I didn’t see pyformat in the list so I thought I’d throw it in:

    console.log(pyformat( 'The {} {} jumped over the {}' , ['brown' ,'fox' ,'foobar'] )) console.log(pyformat('The {0} {1} jumped over the {1}' , ['brown' ,'fox' ,'foobar'] )) console.log(pyformat('The {color} {animal} jumped over the {thing}' , [] ,{color: 'brown' ,animal: 'fox' ,thing: 'foobaz'} )) 
  24. /** * Format string by replacing placeholders with value from element with * corresponsing index in `replacementArray`. * Replaces are made simultaneously, so that replacement values like * '{1}' will not mess up the function. * * Example 1: * ('{2} {1} {0}', ['three', 'two' ,'one']) -> 'one two three' * * Example 2: * ('{0}{1}', ['{1}', '{0}']) -> '{1}{0}' */ function stringFormat(formatString, replacementArray) { return formatString.replace( /{(d+)}/g, // Matches placeholders, e.g. '{1}' function formatStringReplacer(match, placeholderIndex) { // Convert String to Number placeholderIndex = Number(placeholderIndex); // Make sure that index is within replacement array bounds if (placeholderIndex < 0 || placeholderIndex > replacementArray.length - 1 ) { return placeholderIndex; } // Replace placeholder with value from replacement array return replacementArray[placeholderIndex]; } ); } 
  25. another suggestion is you use the string template:

    const getPathDadosCidades = (id: string) => `/clientes/${id}` const getPathDadosCidades = (id: string, role: string) => `/clientes/${id}/roles/${role}` 
  26. I did not see the String.format variant:

    String.format = function (string) { var args = Array.prototype.slice.call(arguments, 1, arguments.length); return string.replace(/{(d+)}/g, function (match, number) { return typeof args[number] != "undefined" ? args[number] : match; }); }; 
  27. String.prototype.format = function () { var formatted = this; for (var prop in arguments[0]) { var regexp = new RegExp('\{' + prop + '\}', 'gi'); formatted = formatted.replace(regexp, arguments[0][prop]); } return formatted; };
  28. With sprintf.js in place – one can make a nifty little format-thingy

    String.prototype.format = function(){ var _args = arguments Array.prototype.unshift.apply(_args,[this]) return sprintf.apply(undefined,_args) } // this gives you: "{%1$s}{%2$s}".format("1", "0") // {1}{0} 
  29. There is also Globalize.format in the jQuery Globalize project, the official globalization service for jQuery UI. IT’s nice when you need culture-aware formatting.

  30. I needed a function which could format a price (given in cents) in a way preferred by the user, and the tricky part is that the format is specified by the user — and I do not expect my users to understand printf-like syntax, or regexps, etc. My solution is somewhat similar to that used in Basic, so the user just marks with # places for digits, for example:

    simple_format(1234567,"$ ###,###,###.##") "$ 12,345.67" simple_format(1234567,"### ### ###,## pln") "12 345,67 pln" 

    I believe this is quite easy to understand by user, and quite easy to implement:

    function simple_format(integer,format){ var text = ""; for(var i=format.length;i--;){ if(format[i]=='#'){ text = (integer%10) + text; integer=Math.floor(integer/10); if(integer==0){ return format.substr(0,i).replace(/#(.*#)?/,"")+text; } }else{ text = format[i] + text; } } return text; } 
  31. arg function:

    /** * Qt stil arg() * var scr = "<div id='%1' class='%2'></div>".arg("mydiv").arg("mydivClass"); */ String.prototype.arg = function() { var signIndex = this.indexOf("%"); var result = this; if (signIndex > -1 && arguments.length > 0) { var argNumber = this.charAt(signIndex + 1); var _arg = "%"+argNumber; var argCount = this.split(_arg); for (var itemIndex = 0; itemIndex < argCount.length; itemIndex++) { result = result.replace(_arg, arguments[0]); } } return result; } 
  32. String.prototype.format = function(){ var final = String(this); for(let i=0; i<arguments.length;i++){ final = final.replace(`%s${i+1}`, arguments[i]) } return final || '' } console.log(("hello %s2 how %s3 you %s1").format('hi', 'hello', 'how'));
    <h1 id="text"> </h1>

  33. In typescript create a file named format.ts and import it whatever you need to use formatting.

    // contents of format.ts interface String { format(...args: any[]): string; } if (!String.prototype.format) { String.prototype.format = function() { let a = this; let b: any; // tslint:disable-next-line: forin for (b in arguments) { a = a.replace(/%[a-z]/, arguments[b]); } return a; }; } 

    To format string use this code:

    import './format'; console.log('Hello, %s!'.format('World')); 

    Example

    String.prototype.format = function() { let a = this; let b; for (b in arguments) { a = a.replace(/%[a-z]/, arguments[b]); } return a; }; console.log('Hello, %s!'.format('World'));

  34. if you just need to format a string with %s specifier only

    function _sprintf(message){ const regexp = RegExp('%s','g'); let match; let index = 1; while((match = regexp.exec(message)) !== null) { let replacement = arguments[index]; if (replacement) { let messageToArray = message.split(''); messageToArray.splice(match.index, regexp.lastIndex - match.index, replacement); message = messageToArray.join(''); index++; } else { break; } } return message; } _sprintf("my name is %s, my age is %s", "bob", 50); // my name is bob, my age is 50 
  35. Right now, there is a package called locutus which translate the functions of other languages to Javascript such as php, python, ruby etc.

    const printf = require('locutus/php/strings/printf') printf('Hello world'); 

    You can try this playground codesandbox

  36. Ok, so first we’ll set up some variables to use:

     const date = new Date(); const locale = 'en-us'; const wDay = date.toLocaleString(locale, {weekday: 'short'}); const month = date.toLocaleString(locale, {month: 'long'}); const year = date.toLocaleString(locale, {year: 'numeric'}); const minute = date.toLocaleString(locale, {minute: 'numeric'}); const [hour, ap] = date.toLocaleString(locale, {hour: 'numeric', hour12:true}).split(' '); let mDay = date.toLocaleString(locale, {day: 'numeric'}); switch(mDay % 10) { case 1: mDay += 'st'; break; case 2: mDay += 'nd'; break; case 3: mDay += 'rd'; break; default: mDay += 'th'; break; } 

    Now that we’ve got all that, we can format a string like so:

     const formatter = (...a) => `${a[0]}, the ${a[1]} of ${a[2]} ${a[3]} at ${a[4]}:${a[5]} ${a[6]}`; const formatted = formatter(wDay, mDay, month, year, hour, minute, ap); 

    We could even use named paramaters for the “formatter” function:

     const formatter = (wDay, mDay, month, year, hour, minute, ap) => `${wDay}, the ${mDay} of ${month} ${year} at ${hour}:${minute} ${ap}`; const formatted = formatter(wDay, mDay, month, year, hour, minute, ap); 

    If you’ll notice, the JS templates above are both the results of callbacks. If the entire piece of code above were encapsulated within a function that was expected to return a formatted date, it would not be hard to imagine how to construct an arbitrary “formatter” function in the same manner, that could be passed in from outside.

    tl;dr you can re-use template literals if you put them inside callbacks and use the args as the replacements.

  37. String.prototype.format = function format() { var msg = this; for(var i in arguments) msg = msg.replace(/{}/,arguments[i]).replace(new RegExp('\{'+i+'\}','g'),arguments[i]); return msg; }
  38. You can use this function

     String.prototype.format = function (args) { var str = this; return str.replace(String.prototype.format.regex, function(item) { var intVal = parseInt(item.substring(1, item.length - 1)); var replace; if (intVal >= 0) { replace = args[intVal]; } else if (intVal === -1) { replace = "{"; } else if (intVal === -2) { replace = "}"; } else { replace = ""; } return replace; }); }; String.prototype.format.regex = new RegExp("{-?[0-9]+}", "g"); // Sample usage. var str = "She {1} {0}{2} by the {0}{3}. {-1}^_^{-2}"; str = str.format(["sea", "sells", "shells", "shore"]); alert(str); 
  39. bobjs can do this:

    var sFormat = "My name is {0} and I am {1} years old."; var result = bob.string.formatString(sFormat, "Bob", 29); console.log(result); //output:  //==========  // My name is Bob and I am 29 years old.  
  40. String.prototype.repeat = function(n) { return new Array(++n).join(this); }; String.prototype.pad = function(requiredLength, paddingStr, paddingType) { var n = requiredLength - this.length; if (n) { paddingType = paddingType ? paddingType.toLowerCase() : ''; paddingStr = paddingStr || ' '; paddingStr = paddingStr.repeat( Math.ceil(n / paddingStr.length) ).substr(0, n); if (paddingType == 'both') { n /= 2; return paddingStr.substr( 0, Math.ceil(n) ) + this + paddingStr.substr( 0, Math.floor(n) ); } if (paddingType == 'left') { return paddingStr + this; } return this + paddingStr; } return this; }; // синтаксис аналогичен printf // 'Привет, %s!'.format('мир') -> "Привет, мир!" // '%.1s.%.1s. %s'.format('Иван', 'Иванович', 'Иванов') -> "И.И. Иванов" String.prototype.format = function() { var i = 0, params = arguments; return this.replace(/%(?:%|(?:(|[+-]+)(|0|'.+?)([1-9]d*)?(?:.([1-9]d*))?)?(s|d|f))/g, function(match, sign, padding, width, precision, type) { if (match == '%%') { return '%'; } var v = params[i++]; if (type == 'd') { v = Math.round(v); } else if (type == 'f') { v = v.toFixed(precision ? precision : 6); } if (/+/.test(sign) && v > 0) { v = '+' + v; } v += ''; if (type != 'f' && precision) { v = v.substr(0, precision); } if (width) { v = v.pad(width, padding == '' ? ' ' : padding[0] == "'" ? padding.substr(1) : padding, /-/.test(sign) ? 'right' : 'left'); } return v; }); }; // this.name = 'Вася'; // console.log( 'Привет, ${name}!'.template(this) ); // "Привет, Вася!" String.prototype.template = function(context) { return this.replace(/${(.*?)}/g, function(match, name) { return context[name]; }); };

Tasg: html, redirect