如何以角4路线

Sam*_*ler 9 apache angular angular4-router

我有一个角度4项目,当我运行它时localhost:4200/route-a,它工作正常,当我刷新浏览器时,一切都按预期工作.但是,当我使用ng buildapache 构建它并从apache运行它时,导航localhost/route-a返回a 404.这是我的路由代码:

imports: [BrowserModule, HttpModule, FormsModule, RouterModule.forRoot([
    { path: 'home', component: HomeComponent },
    { path: 'route-a', component: RouteAComponent },
    { path: '', redirectTo: '/home', pathMatch: 'full' }
  ])]
Run Code Online (Sandbox Code Playgroud)

Doe*_*ehl 24

这不是一个角度问题.这是您的Apache设置的问题.当您在Angular中使用HTML5模式(漂亮网址)时,您必须配置您的Apache以将服务器上不存在资源的所有请求发送到index.html文件.

这可以通过以下.htaccess配置来完成:

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
Run Code Online (Sandbox Code Playgroud)

原因是当您尝试访问时/route-a,apache服务器将默认尝试查找目录route-a和index.html文件.但是因为你没有该目录,apache会返回404错误.

但是通过告诉apache,在任何位置或文件不存在的请求上.要发送您发送的Angular html文件,Angular路由器会从那里获取它.


小智 5

从Apache 2.2.16版本开始,您可以为此使用FallbackResource指令:

<Directory "/var/www/my_blog">
  FallbackResource index.php
</Directory>
Run Code Online (Sandbox Code Playgroud)

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