5

I have an Angular 4 application deploy on a remote server with Nginx, and accessible with this address: http://xx.xx.xx.xx/app. The app works well, I can navigate in my website but when I refresh one page, for example http://xx.xx.xx.xx/app/page1, it displays the index.html page of nginx.

Nginx's pages are located in /usr/share/nginx/html, and my app's pages are located in /var/www/app.

nginx.conf

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root /usr/share/nginx/html;
        include /etc/nginx/default.d/*.conf;                                                */

        location /app {
            root /var/www;
            try_files $uri $uri/ /index.html;
        }
    }

It seems that the line root /var/www is not taken into account during a refresh.

I heard something about a bug with try_files, and it seems that I need to add a rewrite somewhere. Thanks for help.

Nilesh Khisadiya
  • 1,560
  • 2
  • 15
  • 27
Benjamin Lucidarme
  • 1,648
  • 1
  • 23
  • 39
  • try with something like this: location ~ ^/app/(.*)$ instead of /app . This ensures that it is matching on any subpages not only /app – eesdil Aug 08 '17 at 10:16
  • Did you try to change it to `root /var/www/app;` or `try_files $uri $uri/ /app/index.html;`? – Poul Kruijt Aug 08 '17 at 10:28
  • @eesdil Thanks for suggestion but it doesn't change anything. – Benjamin Lucidarme Aug 08 '17 at 11:37
  • @PierreDuc Your second suggestion doesn't work. But the first is more interesting. The refresh works well now, but when I go to my website, I am redirect on my app directly, and I don't want that. So I tried to write only `root /var/www;` but the behaviour come back as before... – Benjamin Lucidarme Aug 08 '17 at 11:50
  • You should change to `location /app/` (the extra slash). And I guess you can disregard my first comment – Poul Kruijt Aug 08 '17 at 11:58

1 Answers1

3

Try to add this in your AppModule:

import { HashLocationStrategy, LocationStrategy } from '@angular/common';

@NgModule({
    // ...
    providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}],
    // ...
})
export class AppModule {}
Faly
  • 13,291
  • 2
  • 19
  • 37
  • Well... That pretty weird, the URL is little bit impact due to the `/#/` but it seems to be invisible for the user. Could you explain how does it works? Thanks – Benjamin Lucidarme Aug 08 '17 at 12:03
  • 1
    You can find more explanation here: https://stackoverflow.com/questions/35284988/angular-2-404-error-occur-when-i-refresh-through-browser – Faly Aug 08 '17 at 12:13