简体   繁体   中英

JavaScript redirect script if domain name does not match my word

I want to put in my HTML/PHP a script for redirection if the website name does not match my word. I tried to use this code, but it doesn't work.

WITH REGEX

if (window.location.hostname !== 'myword.org'){
    window.top.location.href = 'http://redirecttomysite.org'; 
}

var website = window.location.hostname;
var internalLinkRegex = new RegExp('^((((http:\\/\\/|https:\\/\\/)(www\\.)?)?'
                                     + website
                                     + ')|(localhost:\\d{4})|(\\/.*))(\\/.*)?$', '');

WITHOUT REGEX

if (website !== 'myword.org'){
    window.top.location.href = 'http://redirecttomysite.org/forum'; 
}

try

if (website.indexOf('myword.org') == -1){
    window.top.location.href = 'http://redirecttomysite.org/forum'; 
}

simply as below

if (!(/stackoverflow\.com/i.test(location.hostname))){
...

similar behavior as an HTTP redirect

window.location.replace("http://stackoverflow.com");

similar behavior as clicking on a link

window.location.href = "http://stackoverflow.com";
if(window.location.href.indexOf("myword.org") == -1) {
       window.location = 'http://redirecttomysite.org';
    }

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