简体   繁体   中英

How can I easily handle redirects by JSON in HTML/JavaScript?

I have a directory on my web server called /go/ . In practice, this would be used as https://example.com/go/x where x is a variable stored in a JSON file. The JSON file can be set up like so;

{
    "stackoverflow": "https://stackoverflow.com/",
    "apple":         "https://apple.com/",
    ...
}

I would like to, somehow, check if any of these variables check the /go/x and redirect them to their equivalent. In practice, it would be used like https://example.com/go/stackoverflow and it will redirect me to this site.

I don't want to add multiple HTML files in that directory and redirect from there, as I want to externally manage the JSON responses. That is irrelevant though.

I currently don't already have a solution, but was thinking of a JavaScript script that checks the JSON for any match. I don't know, however, how that script will get run because it never gets hit or called by anything. I already have the script that could get called, but don't know how to call it when /go/x is urgent:

import "Paths.json" as Paths;
if (window.location.pathname == "/go/") {
    const Location = JSON.parse(Paths)[window.location.href];
    window.location.replace(Location);
}

Conclusion : I would like to redirect users to different pages depending on the variable x in /go/x . The redirects are stored in JSON. Every time /go/ gets hit, I would like to run a JavaScript script to check on that variable and redirect the user to another page without adding different HTML files for each redirect and so forth.

You could configure your web server to serve a html file, say redirect.html for /go/* . This preserves the pathname while handling all paths

You could then redirect the user based on the pathname.

Script in redirect.html:

const data = //load data;
const redir = location.pathname.replace("/go/","");
location.href = data[redir];

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