如何根据用户上一页修改当前页URL超链接及制作带返回链接的404页面
Hey there! Let's walk through how to build that dynamic 404 page with a contextual back link tailored to the user's previous page. I'll cover both client-side and optional server-side approaches to make this work smoothly.
1. Basic 404 Page with a "Go Back" Button
The simplest way to let users return to their previous page is using the browser's built-in history API. The window.history.back() method automatically navigates the user to the last page in their browser history—no need to manually fetch or parse URLs.
Here's a complete example with basic styling for better UX:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>404 Not Found</title> <style> .container { text-align: center; padding: 50px; font-family: Arial, sans-serif; } .back-btn { padding: 10px 20px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; } .back-btn:hover { background-color: #0056b3; } </style> </head> <body> <div class="container"> <h1>404 Not Found</h1> <p>Oops! The page you're looking for doesn't exist.</p> <!-- One-click back to previous page --> <button class="back-btn" onclick="window.history.back()">Go Back to Previous Page</button> </div> </body> </html>
This button will take users straight back to pages like www.example.com/products without any extra setup.
2. Manually Fetch Previous Page URL for a Text Link
If you want to display a visible link with the actual URL of the previous page (instead of a button), you can use document.referrer to get the URL of the page that led the user to the 404. Just be sure to add fallbacks for cases where the referrer isn't available.
Example code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>404 Not Found</title> <style> .container { text-align: center; padding: 50px; font-family: Arial, sans-serif; } .back-link { color: #007bff; text-decoration: none; } .back-link:hover { text-decoration: underline; } </style> </head> <body> <div class="container"> <h1>404 Not Found</h1> <p>Oops! The page you're looking for doesn't exist.</p> <div id="backLinkContainer"></div> <script> const previousPageUrl = document.referrer; const backLinkContainer = document.getElementById('backLinkContainer'); const yourDomain = 'www.example.com'; if (previousPageUrl) { // Only link to pages on your own domain for safety if (previousPageUrl.includes(yourDomain)) { const link = document.createElement('a'); link.href = previousPageUrl; link.textContent = `Go back to ${previousPageUrl}`; link.className = 'back-link'; backLinkContainer.appendChild(link); } else { // Fallback if referrer is external backLinkContainer.innerHTML = '<button class="back-btn" onclick="window.history.back()">Go Back</button>'; } } else { // Fallback if there's no referrer (user directly typed the 404 URL) backLinkContainer.innerHTML = '<a href="/" class="back-link">Go to Homepage</a>'; } </script> </div> </body> </html>
Key Notes for This Approach:
document.referrermight be empty if the user directly navigated to the 404 page (e.g., typed the URL) or if their browser blocks referrer data for privacy reasons.- Always validate the referrer domain to avoid linking users to external/malicious sites.
3. Server-Side Approach (More Reliable)
If your site uses a server-side framework (like Node.js/Express, PHP, or Python/Django), you can fetch the referrer from the request headers and pass it to your 404 template. This avoids browser privacy restrictions that might block document.referrer.
Here's an example with Express.js:
// In your Express app setup app.use((req, res, next) => { // Store the referrer in response locals res.locals.previousPage = req.get('Referrer'); next(); }); // 404 route handler app.use((req, res) => { res.status(404).render('404', { previousPage: res.locals.previousPage, yourDomain: 'www.example.com' }); });
Then in your EJS template:
<div class="container"> <h1>404 Not Found</h1> <p>Oops! The page you're looking for doesn't exist.</p> <% if (previousPage && previousPage.includes(yourDomain)) { %> <a href="<%= previousPage %>" class="back-link">Go back to <%= previousPage %></a> <% } else { %> <button onclick="window.history.back()">Go Back</button> <a href="/" class="back-link">Or go to Homepage</a> <% } %> </div>
This method is more reliable because it uses the request header directly, which is less likely to be blocked by browser settings.
Final Tips
- Prioritize Fallbacks: Always have a backup (like a homepage link) for cases where the previous page URL isn't available.
- Keep UX Simple: The 404 page should clearly tell users what went wrong and give them an easy way to get back to your site's main content.
- Test Edge Cases: Try accessing the 404 page directly, from external sites, and from your own domain to make sure all scenarios work as expected.
内容的提问来源于stack exchange,提问作者Steven

