Search code examples
angularspringrefreshjhipster

Delete Hash from URL and refresh without 404 error - Angular 4.3.2 - JHipster


I have a project made with JHipster generator, Angular 4.3.2 and Spring.

All of this in a Monolithic application

In the development area I'm using node for the routing and nginx for the production area.

This project in the url have a hashtag symbol after the url

http://example.com/#

I want to navigate in my single page app without that symbol and also refresh the page without getting 404 not found error.

I made the app to work without the symbol replacing all of this

RouterModule.forRoot... {useHash: true}

To this

RouterModule.forRoot... {useHash: false}

How can I make the app refresh to work without getting error 404?


Solution

  • Here are all of the changes made to remove the hash from the URL for the Angular client. https://github.com/ruddell/jhipster-examples/commit/2c31cf65eea96d45c8ed63845e2d96b04fb4b29f

    The important parts are as follows:

    1. Add ClientForwardController which forwards all unmapped backend routes (anything not an API endpoint) to index.html
        @Controller
        public class ClientForwardController {
            /**
             * Forwards any unmapped paths (except those containing a period) to the client index.html
             */
            @GetMapping(value = "/**/{path:^(?!websocket)[^\\.]*}")
            public String forward() {
                return "forward:/";
            }
        }
    
    1. Change the base href in index.html to /, if you deploy under a context path you will have to configure this value in webpack.common.js

    2. For nginx in production, you have to configure it to send unhandled URLs to index.html. As documented, here's an example that proxies to the API and otherwise sends to index.html:

    server {
        listen 80;
        index index.html;
        server_name localhost;
        error_log  /var/log/nginx/error.log;
    
        root /usr/share/nginx/html;
    
        location /api {
            proxy_pass http://api.jhipster.tech:8081/api;
        }
        location /management {
            proxy_pass http://api.jhipster.tech:8081/management;
        }
        location /v2 {
           proxy_pass http://api.jhipster.tech:8081/v2;
        }
        location /swagger-ui {
            proxy_pass http://api.jhipster.tech:8081/swagger-ui;
        }
        location /swagger-resources {
            proxy_pass http://api.jhipster.tech:8081/swagger-resources;
        }
        location / {
            try_files $uri $uri/ /index.html;
        }
    }