I am working on an angular project with routing and it works fine in local. When I deploy the same in Apache httpd, on browser refresh from any page it gives the error 'The requested URL was not found on this server.'
-
You should rewrite everything (that is not an existing file or folder) to /index.html. There are plenty examples available online. – MikeOne Dec 19 '19 at 20:05
-
https://stackoverflow.com/questions/44819308/how-to-route-in-angular-4 Check this out, see if that works. – Chad K Dec 19 '19 at 20:35
1 Answers
The comments of MikeOne and Chad K are right, that is one way of solving this issue.
Firstly, when you build an app for production ng build --prod sometimes you need to change the base href in the index.html if the app is not in the root of your webserver, I think this is not your problem but you could check it anyway.
After that, let's say your routing is going to 'http://yourserver/page1/' when the app is reloaded from that URL the webserver will try to find a directory named page1 which does not exist.
The proposed solutions on the comments would work, using apache mod rewrite. An that solution would only work if you have access to the configuration files of that server or if it uses .htaccess files, which sometimes is not the case. However, if you don't mind having the URLs a little bit different there is another much simpler solution.
in the import of the RouterModule where there is something like:
RouterModule.forRoot( routes )
You can add the useHash this way:
RouterModule.forRoot( routes, { useHash: true } )
then rebuild your project with the production flag and the URLs now will be like:
http://yourserver/#/page1/
this way, thanks to the hash, the app will work without any problems and the only thing needed is setting the useHash on the RouterModule and rebuilding your app.
- 17,312
- 5
- 45
- 56