Angular-cli: routing doesnt work after deployment in angular2

Created on 25 Oct 2016  路  29Comments  路  Source: angular/angular-cli

angular-cli: 1.0.0-beta.18
node: 6.4.0
os: win32 x64 Windows 10

I have created an angular2 app & deployed it successfully.

app starts correctly after taking some time to load & then I am able to navigate to different components.

but when I put direct address in URL as :

www.sample.com/about

it says 404 error.

even when I am creating bundle using ng build --prod , it creates dist folder correctly & I am able to navigate to different components using links only.

but I cant access components directly from the URL in my local system also.

I am using http-server.

are there any extra configurations required to make it work?

Most helpful comment

@naveenkumarkg19 see https://angular.io/guide/deployment for information about deployment. Likely you need to configure index fallback (https://angular.io/guide/deployment#routed-apps-must-fallback-to-indexhtml).

All 29 comments

you need to setup something to redirect to your index.html page or change the default location strategy to hash.

Hi,

Yes - you do :) Angular CLI does not automatically add routing to the app just yet therefore you would need to modify app.module.ts file as example below:

imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot([
      { path: '', redirectTo: '/home', pathMatch: 'full' },
      { path: 'home', component: HomeComponent },
      { path: 'about', component: AboutComponent },
      {
        path: 'individual',
        component: IndividualComponent,
        data: {
          title: 'User List'
        }
      },
      { path: '', component: AppComponent }

    ]),
    HttpModule,
    JsonpModule,
    AlertModule
  ],

@hbweb HI I tried this,still its not redirecting to components if I am redirecting directly from URL :(

As @deebloo mentioned, you need to properly configure your server or switch to angular's hash location strategy.

+1 Then pushing to gh-pages is probably not much good since we can't update their servers for proper html5mode. Same as with ng1.x, no?

@irthos you can change the router to use A hash location strategy instead of the history API and that will work on gh pages.

http-server doesn't support fallback to index.html, thus you can't use HTML5 push navigation with it.
You can use https://github.com/johnpapa/lite-server instead, which supports fallback.

Hi , I have the same issue , its working on ng serve . But if I use ng build I cant hit directly i get "Error cannot GET/path" . I was not able to implement the the hash location strategy . can somebody help me with this

@naveenkumarkg19 see https://angular.io/guide/deployment for information about deployment. Likely you need to configure index fallback (https://angular.io/guide/deployment#routed-apps-must-fallback-to-indexhtml).

If this issue occurred in production, follow below steps

1) Add a Web.Config file in the src folder of your angular application. Place below code in it.

<configuration>
<system.webServer>
<rewrite>
    <rules>
    <rule name="Angular Routes" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="/" />
    </rule>
    </rules>
</rewrite>
</system.webServer>
</configuration>

2) Add a reference to it in angular-cli.json. In angular-cli.json put Web.config in assets block as shown below.

"assets": [
    "assets",
    "favicon.ico",
    "Web.config"
  ],

3) Now you can build the solution for production using
ng build --prod
This will create a dist folder. The files inside dist folder are ready for deployment by any mode.

Hi. Did anybody tested the last solution above? Is it working?

Nothing Works.... :-(

I have the same issue... "ng serve" works great and changes the url according to route configuration. "ng build --prod" changes the url according to route configuration but they cannot be navigated again

@filipesilva "http-server doesn't support fallback to index.html, thus you can't use HTML5 push navigation with it. You can use https://github.com/johnpapa/lite-server instead, which supports fallback."

that worked for me! I assume this fallback thing is supported in an amazon server as well, right? (we're planning to upload the front end project there)

What worked for me is:

  1. Change the server so it will fall back to index.html
  2. In production, change to use "-d /static/" instead of -b option. This will assure no changes in the URL will come back from angular router

@deebloo Would we still be able to go directly to deep rooted pages and get SEO with that approach?

@Bhushan001 U have to add something like that in ur server.js

app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname + '/dist/index.html'));
});

@amocarski refreshing on any page will lead to index.html only

Create a Web.Config file on the same folder just like MalateshPatil says.

<configuration>
<system.webServer>
<rewrite>
    <rules>
    <rule name="Angular Routes" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="/" />
    </rule>
    </rules>
</rewrite>
</system.webServer>
</configuration>

And nothing more!
Works

You need to configure this on the server, direct access e.g. www.yourdomain.eu/home will look for "home" directory which does not exist... All requests need to go through index.html so on apache server all you need is .htaccess from this https://angular.io/guide/deployment

Had the same issue, fixed like this
I was using changed to this worked for me

But if you are setting it on aws S3 you need to configur s# and cloudfront
https://medium.com/@willmorgan/moving-a-static-website-to-aws-s3-cloudfront-with-https-1fdd95563106

Working example: https://github.com/sunling/random-quote
Heroku link:https://randomquote621.herokuapp.com/

Angular Deployment guide: https://angular.io/guide/deployment

find this line , it should be in routes file
RouterModule.forRoot(appRoutes);

and change it to
RouterModule.forRoot(appRoutes, {useHash: true});

2nd solution : keep this as your last route, if you dont like hash based urls
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname + '/dist/index.html'));
});

Apache: add a rewrite rule to the .htaccess file with following content

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

Apache: add a rewrite rule to the .htaccess file with following content

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

This work for me !!

For Apache Server

  • Create a file name .htaccess
  • Edit that file and write index.html instead of index.php
  • For those who dont have any code, can write the code below in your .htaccess file :
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

Adding .htaccess file to my root directory worked for me, also check httpd.conf file to ensure rewrite_module is being loaded (by default it's commented.)

This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

_This action has been performed automatically by a bot._

Was this page helpful?
0 / 5 - 0 ratings

Related issues

brtnshrdr picture brtnshrdr  路  3Comments

jmurphzyo picture jmurphzyo  路  3Comments

IngvarKofoed picture IngvarKofoed  路  3Comments

NCC1701M picture NCC1701M  路  3Comments

gotschmarcel picture gotschmarcel  路  3Comments