views:

77

answers:

3

How to automatically replace url in browser address bar with JavaScript
from   company.com/en/services/
to       company.com/en/#services
?
Example: when I type in browser address bar url company.com/en/services/ and click 'Go', it will be automatically seen company.com/en/#services

Is there any way to replace real url /services/ with hash url /#services without browser refresh and no redirecting? Does jQuery has some solution for that?

+3  A: 

You can't change the URL with Javascript for the current page. You can only change the hash like this (without causing a refresh):

window.location.hash = '#services';

So when you're at the page company.com/en/ and then click something, you could then set the window.location.hash. For example, it could be changed to company.com/en/#anything_you_set. The only other way is to do what Pekka suggested and reload the page.

If you want them to type the url and have it change to the hash, you're going to have to look up URL Rewriting (at least for ASP.NET and IIS). If you're on IIS7, you can use the URL Rewrite Module.

If you're on apache, you can read this URL rewrite tutorial.

TheCloudlessSky
Or you can configure the server to send an HTTP 301 redirect to the `company.com/en/#services` URL when `company.com/en/services/` is accessed.
abhin4v
@abhin4v: most browsers don't support a redirect to a hash. So people will end up at /en/ only.
Jonathan Hedley
A: 

You could do something like this:

 $(document).ready(function() {
     window.document.location.href = 'company.com/en/#services'
 });
Jeff V
A: 

I'd go with:

<script>
document.replace("/en/#services");
</script>
<meta http-equiv="refresh" content="0;url=/en/#services" />

on /en/services/

Document.replace(url) will have the browser load the new page, and the old one won't be in the history, so when the user hits back, they won't get stuck in loop. The meta catches people without JS.

I don't think that you can't reliably do this with a server-side redirect, as many browsers (and the HTTP spec) consider the hash client-side only, and so it doesn't survive the redirect.

Jonathan Hedley