简体   繁体   中英

Javascript redirect to same folder on different domain?

I'm trying to redirect users from one site to another but keep the part after the domain name the same. For example:

http://www.mysite.com/this-is-a-blog-post.html

to

http://www.newwebsite.com/this-is-a-blog-post.html

Can this be done using a javascript redirect? If so, what would the code look like? I appreciate your help!

Check out the window.location object. If you just want to change the domain (keeping the same path) use this code.

window.location = "http://newwebsite.com/" + window.location.pathname;

If you want to do anything more sophisticated, you can mess with the window.location.pathname value and use that to redirect.

To change just the domain and leave everything else (including protocol, port, query string, hash, etc), I'd use...

window.location.hostname = 'example.com';

jsFiddle .

Append window.location.search also if you need query parameters in the url as well.

 open() { var win = window.open('https://newebsite.com/' + window.location.pathname + window.location.search, '_blank'); win.focus(); }
 <button onclick="open()">Open</button>

I think you need to see your dns configuration to do that properly. Your Cname A record can be used to create aliases. Is it worth this hack, long term you would be better of saying we have moved ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM