Serving an Angular2 CLI built app using Nginx throws 404, 403
There could be one of the possibility, that's why you are getting errors 404/403:
- Wrong base href in index.html head tag
- Wrong --base-href value while ng build command
- Wrong nginx configuration(i.e. server root OR server location /)
- Wrong rights to the files(i.e. /dist folder) that Nginx have to serve
Here is the solution:
Suppose you want to deploy your angular app at HOST: http://example.com
and PORT: 8080
Note - HOST and PORT might be different in your case.
Make sure you have <base href="/">
in you index.html head tag.
Also, check that you have correct rights to /dist files which Nginx have to serve. Here is the help.
Firstly, go to your angular repo (i.e. /home/user/helloWorld) path at your machine.
Then build /dist for your production server using the following command:
ng build --prod --base-href http://example.com:8080
Now copy /dist (i.e. /home/user/helloWorld/dist) folder from your machine's angular repo to the remote machine where you want to host your production server.
Now login to your remote server and add following nginx server configuration.
server { listen 8080; server_name http://example.com; root /path/to/your/dist/location; # eg. root /home/admin/helloWorld/dist index index.html index.htm; location / { try_files $uri $uri/ /index.html; # This will allow you to refresh page in your angular app. Which will not give error 404. }}
Now restart nginx.
That's it !! Now you can access your angular app at http://example.com:8080
Hope it will be helpful.