Using Angular 2 RC 4 with the updated @angular/router, I got the route URLs to display in the browser using the answer in this question
However, when I refresh or directly request a page with a route other than the default, it takes me to the default page (as if I requested index.html) rather than the routed page I want. How can I make the Angular 2 routes work correctly on a page refresh with Apache 2.4?
Routes and bootstrap:
const routes: RouterConfig = [
{ path: '', redirectTo: 'dashboardTab', terminal: true },
{ path: 'dashboardTab', component: DashboardComponent },
{ path: 'missionTab', component: MissionComponent, children: childRoutes }];
bootstrap(NavbarComponent, [disableDeprecatedForms(), provideForms(), provideRouter(routes), {provide: Window, useValue: window}, HTTP_PROVIDERS, ResponsiveState, {provide: PLATFORM_DIRECTIVES, useValue: RESPONSIVE_DIRECTIVES, multi: true}]).catch((err: any) => console.error(err));
base href in index.html:
<base href="/">
Basically apache does not know anything about your angular application routes so it can't do much here.
But
Trick here is to get your apache server to serve index.html
file even in page not found situations so that angular then can render the routes.
Here are the steps
.htaccess
inside of your angular applicaiton src
folder, and copy the following code to it
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
RewriteRule ^ /index.html
You need to add this .htaccess
file to the assets
array in your angular.json
so that angular will copy it to your dist
folder when you do a production build.
finally after creating a production build if you copy your application to apache server everything should work fine, but in case if it does not you may want to do the last step
go to /etc/apache2/apache2.conf
inside your server and modify
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
To look like this
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
If that does not work probably you might not have enabled mod rewrite
sudo a2enmod rewrite
See the deployment guide from angular team