valid URL to redirect to

Viewed 39

I have a weird situation where I have a list of urls written by my users (sometimes with omitting https, e.g. www.google.com or google.com), I would like to redirect to those URLs but I am not sure should I append "http://" or "https://", is there an accepted way or library to convert them to proper redirect links to use in express res.redirect("url").

Let me be more clear:

Here is a working express code:

res.redirect("http://www.google.com")

and the one I have with error:

res.redirect("google.com")

which redirects me to myhost/google.com. Question is, it doesn't matter how these URLs are written, if you copy and paste them to chrome address bar, they will work. I would like the same functionality in my redirects.

I am sorry if this is just too dumb to ask, I am kind of a newby in express and node.js

1 Answers

You should NOT add the protocol to your link, if the link is a default website, not FTP or any other resource. Indeed, http is obsolete and deprecated for a lot of browsers, and will be no longer for some browsers in short time. And this can be change in the future if SSL certificate become obsolete.

Anyway, you should add it in variable method (not hardcode way) by adding a function that you could modify at the future, something like:

function addhttp($url) {
    if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

or you could do it by database if you have that layer in your app. Then add the http or https to every link at DB layer.

Related