when redirect url how to reserve hash
When you redirect a URL and want to preserve the fragment identifier (the part of the URL following the # hash symbol), it's important to understand that the hash is not typically sent to the server; it's only used on the client side. That means if you are handling redirects on the server side, you generally won't have access to the hash and hence can't directly preserve it in server-side redirects.
However, if you're handling redirects on the client side (e.g., with JavaScript), you have the ability to read and preserve the hash.
Here's how you can handle it in different scenarios:
If you're using JavaScript to perform the redirect, you can easily include the hash in the new URL:
// Get the current hash.
var hash = window.location.hash;
// Redirect to a new URL while preserving the hash.
window.location.href = "http://www.newsite.com/newpage" + hash;
If the redirect is happening on the server, for example, with a 301 or 302 HTTP status code, you can't directly preserve the hash since it's not sent to the server. However, you can use a client-side script to perform the redirect after the server response. For example, in an HTML document, you might include the following:
<!DOCTYPE html>
<html>
<head>
<title>Redirecting...</title>
<script type="text/javascript">
// Wait for the DOM to be loaded before reading the hash.
document.addEventListener("DOMContentLoaded", function() {
var hash = window.location.hash;
window.location.href = "http://www.newsite.com/newpage" + hash;
});
</script>
</head>
<body>
<p>If you are not redirected, <a href="http://www.newsite.com/newpage">click here</a>.</p>
</body>
</html>
One more approach is to include the hash directly within the Location header in a server response. However, since the hash is not sent to the server, you would need to have prior knowledge of it or use some sort of client-side script to append the hash to a query parameter that the server can read and then use that to construct the full redirect URL including the hash.
<?php
// Assuming you've somehow gotten the hash into a query parameter named 'hash'.
$hash = isset($_GET['hash']) ? $_GET['hash'] : '';
header("Location: http://www.newsite.com/newpage#" . $hash);
exit();
?>
Please be aware that manipulating the hash via server-side code like this is unconventional and may not be reliable, as it depends on the client passing the hash to the server in a non-standard way (like a query parameter).