0

I'm creating an Angular 9 application with a Loopback 4 backend using nginx.

When using ng serve I can navigate to different pages and refresh the page without issue. However after pushing to the staging server, I can navigate the app but if I refresh any page that isn't staging.mydomain.com/ I get a 404 error.

I've tried adding try_files $uri $uri/ /index.html; to the location section of my nginx.conf file, but when I do that the even the index page doesn't load any more.

Below you'll see the the server section of my nginx.conf file:

server {

  listen       443 ssl http2;
  listen       [::]:443 ssl http2;
  server_name  staging.mydomain.com; # managed by Certbot
  root         /usr/share/nginx/html;
  ssl_certificate /etc/letsencrypt/live/staging.mydomain.com/fullchain.pem; # managed by Certbot
  ssl_certificate_key /etc/letsencrypt/live/staging.mydomain.com/privkey.pem; # managed by Certbot

  # Load configuration files for the default server block.
  include /etc/letsencrypt/options-ssl-nginx.conf;

  add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

  location / {
    #try_files $uri $uri/ /index.html;
    proxy_pass http://127.0.0.1:3004;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Conneciton 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
  }

}

server {
  listen 80;
  server_name staging.mydomain.com;
  return 301 https://staging.mydomain.com$request_uri;
}

Is anybody able to provide some guidance to get my deep links working correctly?

John Tiggernaught
  • 758
  • 1
  • 6
  • 25

2 Answers2

0

Try adding an additional / at the end of your proxy-pass statement.

location / {
    #try_files $uri $uri/ /index.html;
    proxy_pass http://127.0.0.1:3004/;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Conneciton 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
  }
  • Note the dire importance of the trailing slash in proxy_pass, which automatically alters the $uri variable to have the /foo on the front-end correspond with / on the backend. No need for an explicit rewrite directive.
Dhruv Shah
  • 1,611
  • 1
  • 8
  • 22
  • I just tried that, but it didn't work I'm afraid. I still got the 404 error page. I also tried un-commenting the `try_files` but that resulted in a blank white page. – John Tiggernaught Jun 25 '20 at 10:59
0

Ouch, this wasn't an nginx issue. It was a Loopback configuration issue.

I added the following to my application.ts file to forward all uncaught requests to index.html for Angular to capture and process.

this.static('*', path.join(__dirname, '../public/index.html'));

Once I added that static path, everything started working correctly.

John Tiggernaught
  • 758
  • 1
  • 6
  • 25