Quick note
Nginx is a high performance web server with some additional capabilities such as load-balancing and reverse-proxy.
Angular is one of the most popular framework for building single page applications.
Angular apps can be connected to a Node js server and deployed but in most cases deployment with a simple web server would be suffice.
Angular can use either of the two routing strategies:
- Hash Routing
- Path Routing (default for Angular)
Path Routing utilizes the new HTML 5 push state API for routing. Therefore we need a web server capable of working with the HTML 5 push state API.Well most web servers don’t work this way out of the box. In these cases the hash routing strategy can be used, but tends to make the URL look messy. Nginx can be configured to deploy any Angular App with HTML 5 push state API.
Build your Angular app by using the command
ng build --prod
Create a new folder under /var/www , usually the domain name of your app, let us assume to be example.com
sudo mkdir /var/www/example.com
copy the contents /dist/appname to /var/www/example.com
Nginx utilizes server blocks to host multiple domains on an single server, you to need to make certain changes to the configuration file
sudo nano /etc/nginx/sites-enabled/default
Add the configuration
server{
listen 80;
listen [::] 80;
server_name www.example.com example.com;
root /var/www/example.com;
index index.html;
location / {
try_files $uri$args $uri$args/ /index.html;
}
}
The configurations are:
- Nginx listens on port 80
- server name is the domain name with www and without it
- root points to location of the app
- index points to initial page to be loaded
- location refers path that should be pointed to on the url patterns, all routes will point to index.html, if this is not added, on refreshing the page Nginx throws a 404 error.
- Note: Use wildcard route pattern in angular to catch 404 errors
const routes: Routes = [
{path:"**",component: PagenotfoundComponent}
];
Restart Nginx
sudo service nginx restart
Happy coding !!
Top comments (3)
Why angular 2 ?
2+.. .so could be Angular 10.1.x beta
That is correct. Great Information!