Home > Net >  How to redirect using Javascript on all WebPages
How to redirect using Javascript on all WebPages

Time:07-12

I am trying to copy this website: https://pslk.net/testtest, it redirects to https://pastelink.net/testtest using javascript and not server-side redirect.

I know how to redirect using .htaccess:

RewriteEngine on
RewriteRule ^(.*)$ https://example2.com/$1 [R=301,L]

and Javascript:

<script>
location.href = "https://example2.com"   document.location.pathname; 
</script>

But I want to redirect using javascript not htaccess. so My question is: Where should I put my javascript code above for it to be executed on all web pages?

Because I tried to place it in index.html and it did not redirect on all web pages. It will only redirect if I visit the index.html

For example, if I visit this link: example.com/test it should redirect to example2.com/test. but I can't just create multiple folders on my website containing that javascript I am tired , there are multiple numbers of combinations on the website's pathname, and I don't think this website created multiple folders with that javascript redirect: https://pslk.net/testtest2

Sorry I am VERY new on this, Thanks.

CodePudding user response:

You can try it with a timeout function:

<html>
   <body>
      <script>
         setTimeout(function(){
            window.location.href = 'https://stackoverflow.com';
         }, 3000);
      </script>
      <p>Redirect after 3 seconds.</p>
   </body>
</html>

CodePudding user response:

sm3sher is right. You'll have to put the script-tag and its content within the body tags and it should be the last item there.

CodePudding user response:

Based on what you describe having an index.html, it seems like you are not using any server side rendering like php. I also don't think you don't have any templating engine (server side or client side)..

If all your pages are somefile.html then you have to edit all your files manually.

CodePudding user response:

I tried this solution, and now it works:

On .htaccess:

RewriteEngine on
ErrorDocument 404   /index.php

On index.php

<script>
location.href = "https://example.com"   document.location.pathname; 
</script>

So, on a blank website with only index.php exist. Whatever you type on your website's pathname will go to the 404 page. you can set the Custom 404 page using htaccess and from index.php you can now set the Javascript wildcard redirect. Please tell me if you have best alternatives. Thanks

  • Related