问题
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="/">
回答1:
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
- Create a file called
.htaccess
inside of your angular applicaitonsrc
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 theassets
array in yourangular.json
so that angular will copy it to yourdist
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
https://angular.io/guide/deployment
回答2:
Use the code in vhost of apache2:
<Directory /var/www/html/yourproject>
Options Indexes FollowSymLinks
RewriteEngine On
RewriteBase /yourproject
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /yourproject/index.html [L]
</Directory>
And use the code in index.html
<script>document.write('<base href="' + document.location + '" />');</script>
this solves.
来源:https://stackoverflow.com/questions/38751327/angular-2-routing-not-working-on-page-refresh-with-apache