404 Not Found nginx angular routing

冷暖自知 提交于 2019-11-30 07:09:05
Sven Dhaens

for those not using a Staticfile might wanna try this.

I had the same problem with nginx serving angular. The following is the default config file, probably found somewhere in /etc/nginx/sites-available/yoursite

     location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            try_files $uri $uri/ =404;
    }

but what we acctually want is...

     location / {
            # First attempt to serve request as file, then
            # as directory, then redirect to index(angular) if no file found.
            try_files $uri $uri/ /index.html;
    }
Mad Javad

In your nginx.conf file try using:

try_files $uri $uri/ /index.html;

instead of:

try_files $uri $uri/ =404;

That worked for me on Angular 5 project.

I finally found the answer: After I generated the dist folder.

  • I created a file called Staticfile and put it in the dist folder
  • I opened Staticfile & I added this line pushstate: enabled

pushstate enabled keeps browser-visible URLs clean for client-side JavaScript apps that serve multiple routes. For example, pushstate routing allows a single JavaScript file route to multiple anchor-tagged URLs that look like /some/path1 instead of /some#path1.

This is a problem with the server side not the Angular side of things . It is the servers responsibility to return the index or the landing page for each request in your case nginx.

UPDATE

If you by any means do not have a backend or server where you can configure this there are two workarounds.

  • Using HashLocationStrategy in Angular
  • Making some tweak in index.html file link No -15

Angular applications are single page applications. When you type the address manually you try to route to a location where the application is not running.

You need to edit nginx config to route to your base page.

For me it was a permission issue, Nginx has to be the owner of the directory where you put your dist, i've seen this error in the nginx log file

"root/../../dist/index.html" failed (13: Permission denied)

so i gave permissions to nginx user on the top folder containing my dist

chown nginx . -R //  to give nginx the permissions on the current directory, and everything in it.

and then you have to restart nginx

sudo systemctl restart nginx

and it should work!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!