Reputation: 533
I'm doing some old url redirection with javascript.
My old urls in Google index are something like domain.com/#!about/c3g8
. My new url for about us page is like domain.com/#about
since I have change my site to one paged site.
My old site has had 4 pages without including root page. Each page has had a unique ending. They are -
/c3g8
/cjg9
/cee5
/cce3
The redirections cannot be done in .htaccess because they contain hash(#) character in them. Therefore, I have no choice but javascript. My current redirect js code is as follow
if(document.URL.indexOf(/!|\/c3g8|\/cjg9|\/cee5|\/cce3/)) {
var url_new = document.URL.replace(/!|\/c3g8|\/cjg9|\/cee5|\/cce3/,'');
window.location = url_new;
break;
}
All inner pages redirect properly but home page became a redirect loop and until I press Esc
key twice.
I have this $('a[href^=#]').bind("click", function(event){....
code in my js too. How can I redirect without leading to a redirect loop?
Thanks in advance!
Upvotes: 0
Views: 1563
Reputation: 14590
You're mixing regex matching and indexOf
. The if
condition is always going to evaluate to -1
which is truthy, so the the redirect always happens.
Use regex.test()
instead, and use the g
modifier to tell it to replace all instances...
if(/!|\/c3g8|\/cjg9|\/cee5|\/cce3/.test(document.URL)) {
var url_new = document.URL.replace(/!|\/c3g8|\/cjg9|\/cee5|\/cce3/g,'');
window.location = url_new;
break;
}
Upvotes: 1
Reputation: 1437
Try this:
var url_new = document.URL.replace(/!|\/c3g8|\/cjg9|\/cee5|\/cce3/,'');
if(document.URL !== url_new){
window.location = url_new;
}
Upvotes: 0