The one that can be considered canonical to navigate to a new URL is:
window.location = "https://newurl.com"
If you want to redirect to a different path, on the same domain, use:
window.location.pathname = '/new'
As with most things in programming, there are many ways to perform the same operation.
window is implicit in the browser, you can also do:
location = 'https://newurl.com'
Another way is to set the
href property of
window.location.href = 'https://newurl.com'
location also has an
assign() method that accepts a URL, and performs the same thing:
replace() method is different than the previous ways because it rewrites the current page in the history. The current page is wiped, so when you click the “back” button, you go back to the page that now is the last visited one.
This can be convenient in some situations.
The above examples all consider the case of a programmatic decision to move away to a different page.
If you need to redirect because the current URL is old, and move the a new URL, it’s best to use server-level directive and set the 301 HTTP code to signal search engines that the current URL has permanently moved to the new resource.
This can be done via
.htaccess if using Apache. Netlify does this through a
That’s not possible to do on the client-side.
Another option is using a meta tag in your HTML:
<html> <head> <meta http-equiv="refresh" content="0;URL=https://newurl.com/"> </head> </html>
This will cause the browser to load the new page once it has loaded and interpreted the current one, and not signal search engines anything. The best option is always to use a 301 server-level redirect.
Different ways to reach the
The browser exposes the
top objects, which all reference the
window object, so you can use them instead of
window in all the examples above:
self.location = 'https://newurl.com' top.location = 'https://newurl.com'
- 0using namespace std is bad
- 0C++: delete single object using delete
- 1C++: Can I call class constructor from another constructor ?
- 0Iterate over tokens using std::regex
- 0How to provide command line arguments using gdb within a bash script
- 0C++: avoid 'using namespace'
- 0typedef vs using in C++11
- 0How to keep a flex container all in one page without scroll
- 0How to disable available times looping through an array using watch?