Search code examples
angularnginxdevopsdevops-services

How to navigate in server using angular


I make a angular application My angular application is running on nginx server . When I type “http://.8.100.248:30749” it show nginx is running. (Showing default index.html). But my application is present in html folder having folder name test. So my application present in “html —> test—> index.html”; When I type “http://.8.100.248:30749/text/index.html” it show my home page .Now I can navigate from one page to another page on button click example . http://.8.100.248:30749/test/page_1**.But when I reload this page http://**.8.100.248:30749/test/page_1 nginx show me 404 page

So when I type http://**.8.100.248:30749/test/index.html. .my application run on browser.but when I route from one page to another and reload my page it gives me 404 example (http://**.8.100.248:30749/test/page_1) .

Nginx gives me 404 when I reload my angular routed page. So I want to change the nginx config

     location / {
           root   /usr/share/nginx/html;
           index  index.html index.htm;
   }

can you please suggest me the way . ? it is doing behaviour because there is no index.html file in this location (http://**.8.100.248:30749/test/page_1)

see update

location / {
           root   /usr/share/nginx/html;
           index  index.html index.htm;
           try_files $uri $uri/ /index.html;
   }

New update

server {
    listen       80;
    server_name  localhost;
    root   /usr/share/nginx/html;
    index  index.html index.htm;

    #charset koi8-r;
    #access_log  /var/log/nginx/log/host.access.log  main;

   location / {
      try_files $uri $uri/ /index.html;
   }

Solution

  • This is because initially, you are able to navigate due to Angular routes, however, on page refresh, the request goes through Nginx again and Nginx is unable to find the route.

    Add this to your Nginx config :

    try_files $uri $uri/ /index.html;

    A sample Nginx server block that solves your issue is as follows:

    server {
        listen 80;
        listen [::]:80;
    
        root /var/www/example.com/html;
    
        index index.html index.htm index.nginx-debian.html;
    
        server_name example.com www.example.com;
    
        location / {
            try_files $uri $uri/ /index.html;
         }
    }
    

    UPDATE :

    Since your index.html resides inside the test directory, Use this

    try_files $uri $uri/ /test/index.html;