-1

Can't use htaccess, so have to rely on javascript.

Say the url is example.com/page1/page2/page3/ and I want to redirect this to example.com/page4/page3/ how would I do this? (and have this work for anything that has anything as page3 and has any subfolders after that as well). And also that page3 can be anything, so a wildcard would have to be in place for this..

Plus: Say the url is example.com/page1/page2/page3/page5/183/ and I want to redirect this to example.com/page4/page3/ how would I do this? (cutting off page5 plus anything on the url after that).

2
  • rely on javascript If you mean javascript running in a browser you would need to make the urls valid before using them. If you mean javascript running on the server it should be pretty easy. Please clarify. Commented Jan 30 at 17:59
  • @James I meant in a browser. Commented Jan 30 at 18:36

2 Answers 2

0

Test the contents of the current URL's pathname; if it startsWith("/page1/page2/page3") then do the redirect:

const currentPath = new URL(window.location.href).pathname;
if (currentPath.startsWith("/page1/page2/page3"))
     window.location.replace("/page4/page3");
Sign up to request clarification or add additional context in comments.

2 Comments

Would it be possible to read out those tags (page1, page2, etc.)? And then if page1=something1 && page2=something2 then do the window.location.replace, else if page1=something1 && page2=something3 then window.location.replace, etc? So that whatever page3 is (wildcard?) that can always be dynamic?
You could split the pathname on "/" and process it however you want from there. currentPath.split("/")
-1
var pathArray = window.location.pathname.split('/');
var LvlLoc1 = pathArray[1];
var LvlLoc2 = pathArray[2];
var LvlLoc3 = pathArray[3];
var LvlLoc4 = pathArray[4];

then do if statements to verify if LvlLoc1-4 are anything and then do a location.href="https://example.com/" + whatever you want it to be. As in my example the url is example.com/page1/page2/page3/ and I want to redirect this to example.com/page4/page3/:

location.href = "https://example.com/" + LvlLoc4 + "/" + LvlLoc3 + "/"

I hope that helps anyone out.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.