How to redirect page to another page
How to redirect page to another page
How to Redirect to Another Web Page Using JavaScript?
Learn about JavaScript redirection and associated issues and pitfalls, and impact on SEO
In this article we’ll look at different ways we can use to redirect to a new web page (or a resource) using only JavaScript. In addition to that we’ll also be exploring the potential fallbacks you can put in place when JavaScript is disabled, the SEO impact of using JavaScript for redirection purposes and alternative solutions.
Redirect Using JavaScript
Ideally, a redirect should be issued from the backend with correct HTTP redirect headers sent to the client. But if we must redirect from JavaScript, we can do so using the methods below:
In most cases, the replace() function might be the best option as it won’t cause redirect loops when users hit the browser’s back button.
Some browsers and most web crawlers may not execute JavaScript for various reasons, which is why having a fallback in place is a good idea.
Fallback When/If JavaScript Is Disabled:
Preferably, we should issue HTTP headers originating from the backend (server-side) to issue a redirect with appropriate redirection code. However, since we’re specifically talking about JavaScript / Frontend redirection, we could use HTML’s meta tag refresh (in the section of the web page) to instruct the browser to refresh the current web page (or an iframe ) after a specified time interval (in seconds). Consider the following example:
The 0 specified in the content attribute instructs the browser to redirect immediately. Changing it to a positive non-zero value would instruct the browser to wait before refreshing the page (the value is interpreted in seconds).
Additionally, we can place a fallback, for example a link, for older browsers in case the meta refresh doesn’t work:
To make sure, the code only executes when/if the browser has JavaScript disabled, we could wrap the meta tag (or other relevant code) inside a noscript tag like so:
Potential Side-Effects:
JavaScript Redirect’s Impact on SEO:
Why a JavaScript Redirect May Impact Your Search Engine Ranking Negatively:
Like mentioned previously, most web crawlers may not execute JavaScript which may negatively impact your web page’s search engine ranking. You might imagine using meta refresh would resolve the issue for all web crawlers, but such is not the case. In fact, an HTML page that contains a meta refresh element returns an HTTP status code of 200 OK (which is different from redirect status codes such as 301, 302, etc.). How that HTML 200 OK response (with a meta refresh tag) is processed and/or interpreted by a user-agent/bot/crawler depends entirely on the agent, its specific purpose and its programming.
Alternatives to JavaScript Redirect, Without Compromising SEO:
The best way to overcome these issues may be:
Although a 404 may be considered bad for SEO in most cases, it may still be more meaningful in some. To help determine what course of action may be best suited in your particular case, you might want to ask yourself the following:
Redirect Immediately After Page Load
By simply placing the redirect code in the section of the webpage (wrapped in script tag of course) we can issue an immediate redirect. For example:
Or, as an alternative, we could also use an inline onload event on the body tag like so:
In this case, however, you must note that everything that preceedes the body tag will be parsed by the browser first.
Redirect When Web Page Loads:
If you wish to make sure the web page finishes loading, or certain scripts etc. load before issuing a redirect, depending on exactly when you intend to do it, you may benefit from the following three events in this particular case:
Examples:
Redirect After a Certain Period of Time Has Elapsed
To delay the redirect by a few seconds, we can use JavaScript’s setTimeout function like so:
Hope you found this post useful. It was published 22 Mar, 2017 (and was last revised 01 Jun, 2020 ). Please show your love and support by sharing this post.
Every developer has a
tab open to
Stack Overflow
A public platform building the definitive collection of coding questions & answers
A community-based space to find and contribute answers to technical challenges, and one of the most popular websites in the world.
A private collaboration & knowledge sharing SaaS platform for companies
A web-based platform to increase productivity, decrease cycle times, accelerate time to market, and protect institutional knowledge.
Thousands of organizations around the globe use Stack Overflow for Teams
Capture your company’s knowledge and context in a discoverable format to unblock your team
Increase productivity
If somebody somewhere has the right answer, suddenly you have it too. Collaborate better in a remote-first world.
Accelerate time to market
Shorten the time between initial idea and complete product. Take delays and misinformation out of the equation.
Protect institutional knowledge
People come and people go, but if you capture their contributions in one central place, that expertise sticks around.
Ensure your company stays on course
Here are just a few types of technologists that we help.
DevOps engineers
Shipping new products and features requires teamwork and coordination. Forget checklists and long docs no one ever reads.
Data scientists
Business decisions are better when backed by data. Give visibility to the data that support your strategies.
Software engineers
Help engineers be more efficient and streamline knowledge sharing using a tool they already love and trust.
Support teams
Level up your support by providing information to your customers using a natural interface: questions and answers.
Engineering leaders
Always free up to 50 teammates
Basic
Up to 250 teammates
Business
Enterprise
Integrates with and improves other tools
All plans come with integrations for ChatOps tools Slack & Microsoft Teams in order to cut down on pings, limit distractions and make the tools even more powerful. Business and Enterprise customers get access to Jira, GitHub & Okta integrations.
Robust read and write API
Single sign-on with AD or SAML
Your own customer success representative
99.5% uptime SLA and priority support
Stack Overflow for Teams has been a resource for our entire company. Not only for developers to solve problems, it’s also enabled our sales field to answer technical questions that help them close deals.
Engineers should help solve the hardest questions, the unknowns, where being familiar with how the product was built is essential. But we don’t want to keep answering solved problems over and over again. That’s where Stack Overflow for Teams really helps.
As we started to use [Stack Overflow for Teams] and saw how nice it was to have a repository of information, we started to see it spread to other teams. Our customer support team started using it, our people success team started using it, next thing we knew, we had [Slack] integrations all over the place.
What we love about Stack Overflow for Teams is that it’s a very dynamic tool…there’s just so many ways to use this as a liaison between different teams and different knowledge bases.
Additional products that reach and engage developers & technologists…
Reach the world’s largest audience of developers and technologists
Connecting communities with the specific technologies they use the most
Build your employer brand
Explore technical topics and other disciplines across 170+ Q&A communities
From Server Fault to Super User, much of the Stack Exchange network continues our mission to empower the world to develop technology through collective knowledge. Other sites on the Stack Exchange network further encourage knowledge sharing across topics such as cooking and medicine.
Build a private community to share technical or non-technical knowledge.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
In this article, we are going to learn How to redirect to another page in ReactJS using react-router-dom package. ReactJS is a free and open source front-end library used for building single page applications.
react-router-dom: react-router-dom is a reactJS package, It enables you to implement dynamic routing in a web page.
Approach:
Step 1: Create a basic react app using the following command in your terminal.
Project Structure: After creating the basic react app, the folder structure looks like this,
Folder structure of react-app
Step 2: Make different pages for routing. Here, We are going to create different components for our react-app. So that we route over them for demonstration.
After creating components, the Folder structure looks like this,
Folder structure after making components
Home.jsx
Home Page
About.jsx
About Page
ContactUs.jsx
Contact Us Page
Step 3: Install react-router-dom package.
Here, We are going to install the react-router-dom package in our react-app, using the following command.
After installing react-router-dom package package.json file looks like this,
Step 3: Implement routing using the react-router-dom package. Here, We are going to implement the react-router-dom package in our react-app. To implement this, We have to import some components from the react-router-dom package i.e. BrowserRouter, Switch, Route, and Redirect.
Note: We make an alias of BrowserRouter as Router, just make things simple.
Let’s see all the imported components one by one:
Next.js Redirect from / to another page
I’m new in Next.js and I’m wondering how to redirect from start page ( / ) to /hello-nextjs for example. Once user loads a page and after that determine if path === / redirect to /hello-nextjs
In react-router we do something like:
13 Answers 13
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Update: Next.js >= 12
Now you can do redirects using middleware, create a _middleware.js file inside the pages folder (or any sub folder inside pages)
Update: Next.js >= 10
From Next.js 10 you can do server side redirects (see below for client side redirects) with a redirect key inside getServerSideProps or getStaticProps :
In next.js you can redirect after the page is loaded using Router ex :
If you want to prevent the flashing before the redirect you can use a simple trick :
I would say that in general is not a good/elegant approach to do client redirects when you can use next.config.js redirects or even better use conditional render of components.
I have create a simple repo with all the examples above here.
Caveat
First, you should asses whether you need client-side redirection (within React), server-side redirection (301 HTTP response) or server-side redirection + authentication (301 HTTP response but also having some logic to check authentication).
Server-side redirection are tempting, in particular when you want to «secure» private pages, but you should assess whether you really need them. Usually, you don’t. They induce unexpected complexity, like managing auth token and refresh token. Instead, you may want to add a gateway server, a reverse proxy or whatever upfront server to your architecture for instance to handle those kind of checks.
Keep in mind that Next.js are just React app, and using Next.js advanced features like SSR comes at a cost that should be justified in your context.
Old Next 9.4 answer
Hi, here is an example component working in all scenarios:
The answer is massive, so sorry if I somehow break SO rules, but I don’t want to paste a 180 lines piece of code. There is no easy pattern to handle redirection in Next, if you want to both support SSR and static export.
The following scenarios each need a specific pattern:
Next 9.5 update
As stated by @Arthur in the comments, 9.5 also include the possibilities to setup redirects in next.config.js. The limitations of this feature are not yet clear to me, but they seem to be global redirections, e.g. when you need to move a page or to allow access only during a limited period. So they are not meant to handle authentication for instance, because they don’t seem to have access to the request context. Again, to be confirmed.
Next 10 new doc update
This solution is specific to redirection depending on authentication.
You may also want to check the approach documented in this ticket based on how Vercel’s dashboard works (at the time of writing), that prevents flash of unauthenticated content
Next 10.2 header and cookies based rewrites update
Next 10.2 introduces Rewrites based on headers and cookies. That’s a great way to redirect server-side, based on the presence of an authentication cookie or header.
However, keep in mind that this is not a secure redirection. User can alter their request headers with a false token. You still need a gateway, a reverse proxy or an upfront server to actually check token validity and correctly set the headers.
Edit: note that the URL won’t change. A rewrite points an URL to an existing page of your application, without changing the URL => it allows you to have «virtual» URLs.
Next 12 update
Now middlewares gives you full-control on server-side redirects.
However, keep in mind again, that most of the time a client-side redirect and check is just enough.
Old answer (works, but will have a messy static render)
Semi-official example
It handles both server side and client side. The fetch call is the one that actually get the auth token, you might want to encapsulate this into a separate function.
What I would advise instead
1. Redirect on server-side render (avoid flash during SSR)
This is the most common case. You want to redirect at this point to avoid the initial page flashing on first load.
2. Redirect in componentDidMount (useful when SSR is disabled, eg in static mode)
This is a fallback for client side rendering.
I could not avoid flashing the initial page in static mode add this point, because you can’t redirect during the static build, but it seems better than the usual approaches. I’ll try to edit as I make progress.
How can I redirect a php page to another php page? [duplicate]
I’m a beginner in the programming field. I want to redirect a php page to another one..How is it possible in the most easiest way? My concept is just to move,to the home page from the login page after doing the checking of user id and password.
7 Answers 7
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
While all of the other answers work, they all have one big problem: it is up to the browser to decide what to do if they encounter a Location header. Usually browser stop processing the request and redirect to the URI indicated with the Location header. But a malicious user could just ignore the Location header and continue its request. Furthermore there may be other things that cause the php interpreter to continue evaluating the script past the Location header, which is not what you intended.
What you want and expected is that not logged in users are redirected to the login page, so that only logged in users can delete_everything. But if the script gets executed past the Location header still everything gets deleted. Thus, it is import to ALWAYS put an exit after a Location header, like this:
So, to answer your question: to redirect from a php page to another page (not just php, you can redirect to any page this way), use this:
Источники информации:
- http://stackoverflow.com/questions/503093/how-do-i-redirect-to-another-webpage
- http://www.geeksforgeeks.org/how-to-redirect-to-another-page-in-reactjs/
- http://stackoverflow.com/questions/58173809/next-js-redirect-from-to-another-page
- http://stackoverflow.com/questions/9581268/how-can-i-redirect-a-php-page-to-another-php-page