Express server for an Angular application part 5: redirect non-www to www requests
Express.js is a web application framework for Node.js designed for building web applications, in this series of articles I will explain step by step how i realized an express server with some advanced functions that i use for my single page application made with Angular 7.
I will discuss the 7 main problem that i solved in different articles:
- getting started
- serve files from a bucket
- redirect some calls to an external service
- redirect http to https requests
- redirect non-www to www requests
- limit connections and prevent DDoS
- handle some cache
In this fourth article I will discuss how to redirect http to https requests.
Reference repository
A working example of this project is available at:
https://github.com/mzuccaroli/express_server_for_angular_example the master branch contain the final full project but there’s a dedicated branch for every single article, for this one the reference is:https://github.com/mzuccaroli/express_server_for_angular_example/tree/feature/non-www_to_www_redirects
About environments
Url handling and manipulation could be tricky during local development, like in the previous part of this tutorial “how to redirect http request to https” it’s a good idea use an “_environment” variable to separate local development behaviors from production ones. For more info see this article
Redirect redirect non-www to www requests
For SEO purposes is optimal serve your application pages from a unique URL, a good improvement for your application server is an automatic redirect for non-www requests. The same method could be used to redirect www request to non-www It’s your choice.
Let’s add this code fragment to our application right before the “app.all” declarations:
As you can see the code is very clear: express intercept the requests that not contain “www” and redirect them to the right url.
Like other steps of this tutorial you can run the server with
$node server.js
go to http://localhost:4100 and see the results.
The next step of our path to create a good express server is improve his security by putting some limits to connections and prevent DDOS attacks, that will be discussed in the next article.