Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I redirect all unmatched urls with Express?

I want to redirect all unmatched urls to my homepage. Ie. someone goes to www.mysite.com/blah/blah/blah/foo/bar or www.mysite.com/invalid_url - I want to redirect them to www.mysite.com

Obviously I don't want to interfere with my valid urls.

So is there some wildcard matcher that I can use to redirect requests to these invalid urls?

like image 704
sonicboom Avatar asked May 19 '13 17:05

sonicboom


People also ask

How do I redirect a URL to another URL Express?

The res. redirect() function lets you redirect the user to a different URL by sending an HTTP response with status 302. The HTTP client (browser, Axios, etc.) will then "follow" the redirect and send an HTTP request to the new URL as shown below.

How get full URL in Express?

To get the full URL in Express and Node. js, we can use the url package. to define the fullUrl function that takes the Express request req object. And then we call url.


1 Answers

Add a route at the end of the rest of your routes.

app.all('*', function(req, res) {   res.redirect("http://www.mysite.com/"); }); 
like image 66
Daniel Avatar answered Sep 19 '22 06:09

Daniel