Skip to content

routing doesnt work after deployment in angular2 #2885

Closed

Description

@Bhushan001

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?

Activity

  1. deebloo commented on Oct 25, 2016

    @deebloo
    Contributor

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

  2. hbweb commented on Oct 25, 2016

    @hbweb

    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
      ],
    
    
  3. Bhushan001 commented on Oct 25, 2016

    @Bhushan001
    Author

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

  4. clydin commented on Oct 25, 2016

    @clydin
    Member

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

  5. 34r7h commented on Oct 27, 2016

    @34r7h

    +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?

  6. deebloo commented on Nov 1, 2016

    @deebloo
    Contributor

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

  7. filipesilva commented on Nov 3, 2016

    @filipesilva
    Contributor

    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.

  8. naveenkumarkg19 commented on Jun 22, 2017

    @naveenkumarkg19

    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

  9. filipesilva commented on Jun 28, 2017

    @filipesilva
    Contributor

    @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).

  10. MalateshPatil commented on Nov 6, 2017

    @MalateshPatil

    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>
    
    1. 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"
      ],
    
    1. 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.
  11. lsalim commented on Nov 10, 2017

    @lsalim

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

  12. piyarulpss commented on Nov 17, 2017

    @piyarulpss

    Nothing Works.... :-(

  13. chezihp commented on Nov 28, 2017

    @chezihp

    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

  14. gustavostuff commented on Nov 30, 2017

    @gustavostuff

    @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)

  15. 1 remaining item

  16. 34r7h commented on Dec 1, 2017

    @34r7h

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

  17. amocarski commented on Jan 22, 2018

    @amocarski

    @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'));
    });

  18. toshikverma commented on Feb 4, 2018

    @toshikverma

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

  19. chacabuk commented on Mar 14, 2018

    @chacabuk

    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

  20. tomandquery commented on Apr 25, 2018

    @tomandquery

    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

  21. Gvo87 commented on Jun 7, 2018

    @Gvo87

    Had the same issue, fixed like this
    I was using <a href="https://github.com/settings"
    changed to <a (click)="navTo('/settings')"
    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

  22. sunling commented on Jul 13, 2018

    @sunling
  23. hiteshSharma6 commented on Aug 18, 2018

    @hiteshSharma6

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

  24. codebanesr commented on Aug 31, 2018

    @codebanesr

    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'));
    });

  25. sks40gb commented on Sep 19, 2018

    @sks40gb

    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
    
  26. qqwrv-f10eq commented on Sep 25, 2018

    @qqwrv-f10eq

    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 !!

  27. smitpatelx commented on Oct 3, 2018

    @smitpatelx

    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
    
  28. ali4j commented on May 27, 2019

    @ali4j

    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.)

  29. angular-automatic-lock-bot commented on Sep 9, 2019

    @angular-automatic-lock-bot

    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.

  30. locked and limited conversation to collaborators on Sep 9, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions