How to get to angular 4

I have an angular 4 project, and when I run it from localhost:4200/route-a , it works fine, and when I update the browser, everything works fine as expected. However, when I create it using ng build and run it from apache, switching to localhost/route-a returns a 404 . Here is my routing code:

 imports: [BrowserModule, HttpModule, FormsModule, RouterModule.forRoot([ { path: 'home', component: HomeComponent }, { path: 'route-a', component: RouteAComponent }, { path: '', redirectTo: '/home', pathMatch: 'full' } ])] 
+5
source share
2 answers

This is not an Angular problem. This is a problem with apache settings. When you use HTML5 (pretty url) mode in Angular, you will need to configure your Apache to send the entire request if the resource does not exist on the server in the index.html file.

This can be done with the following .htaccess configuration:

 RewriteEngine On # If an existing asset or directory is requested go to it as it is RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR] RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d RewriteRule ^ - [L] # If the requested resource doesn't exist, use index.html RewriteRule ^ /index.html 

The reason is that when you try to access /route-a Apache by default tries to find the route-a directory and the index.html file inside. But since you do not have this directory, apache will return a 404 error.

But telling apache that with any request where the location or file does not exist. To send your Angular html indsted file to be sent, the Angular router will take it from there.

+14
source

In Apache version 2.2.16, you can use the FallbackResource directive to do this:

 <Directory "/var/www/my_blog"> FallbackResource index.php </Directory> 

Check https://httpd.apache.org/docs/trunk/rewrite/remapping.html#fallback-resource

+2
source

Source: https://habr.com/ru/post/1269315/


All Articles