SoFunction
Updated on 2025-04-04

How to remove #numbers in Angular2+ Detailed explanation of how to remove #numbers in url

Preface

This article mainly introduces the relevant content about removing # numbers in url in Angular2+. This is a problem I have encountered in my work recently. I feel it is necessary to share it with you. I won’t say much below. Let’s take a look at the detailed introduction together.

1. Why remove it?

  • Angular official pointed out: If there is no sufficient reason to use hash style (#), try to use the HTML5 mode routing style;
  • If you configure hash style, there will still be a 404 problem in the deep path of WeChat Pay or Angular;
  • When you need to use tools such as GA, because you cannot get the URL after the # number, you will send a path to it every time the route switch is changed;
  • '#' is a little ugly.

2. How can I remove it?

There are four methods:

  • Front-end + ngx
  • Front-end + Apache
  • Frontend + Tomcat
  • Github Pages / Code Cloud Pages + 404 Pages

2.1 Front-end

head

<base href="/" rel="external nofollow" >


import { ROUTER_CONFIG } from './';
@NgModule({
 imports: [
 ...
 (ROUTER_CONFIG) 
 // (ROUTER_CONFIG, { useHash: true } ) This is written with #of ],})


import { NgModule } from '@angular/core';
import { Routes } from '@angular/router';
export const ROUTER_CONFIG: Routes = [
 {
 ...
 }
];

What happens if you only configure the front-end?

If you only configure the front end, although '#' will be removed, it will be 404 as soon as the page is refreshed, and an error occurred in the path resolution.
Angular is a single-page application. It implements the front-end routing function. The backend can no longer control the routing jump and throw all the business logic that originally belongs to the backend to the front-end.

  • When the user refreshes the page (/life), the request is first submitted to the WebServer background. If the backend route does not have the corresponding page routing management, a 404 error will occur.
  • If the user first visits the homepage() and then jumps to the page (/life), then this jump is a URL managed by the Angular front desk, and access is normal.

Then we ask WebServer to forward all the route URLs managed by Angular to solve the problem of 404, which is the configuration information introduced later.

Thinking: Why is the hash mode not 404?

2.2 ngx configuration

The file contents with '***' are required to configure it yourself

server {
 listen 80; #The port number of the listener server_name my_server_name; # Server Name *** root /projects/angular/myproject/dist; #Position relative to nginx *** index ; #If it exists, end the search process, append this file to the request_uri of the request, and initiate an internal redirect. location / { # / is to match all uri and perform the following operations try_files $uri $uri/ /; #try_files First look for a file named $uri, if not, look for a file named $uri/, if not, look for / }
}

try_files Explanation in detail:

If the requested is /poetry/life, $uri is '/life'. If the '$uri''$uri/' cannot be found, it will fall back to the last option of try_files / initiate an internal "subrequest", which is equivalent to nginx initiating an HTTP request to /poetry/. This request will be caught by location ~ .php$ { ... }, which means entering the FastCGI handler. The specific URI and parameters are passed to FastCGI and WordPress programs in REQUEST_URI, so they are not affected by URI changes.

2.3 Apache

Create a new .htaccess file in the root directory of Apache

RewriteEngine On 
# If the requested existing resources, execute as isRewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR] 
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d 
RewriteRule ^ - [L]
# If the requested resource does not exist, useRewriteRule ^ / 

2.4 Tomcat configuration

Tomcat/conf/Add on file
&lt;error-page&gt;
 &lt;error-code&gt;404&lt;/error-code&gt;
 &lt;location&gt;/&lt;/location&gt;
&lt;/error-page&gt;

2.5 GithubPages / Code Cloud Pages + 404 Pages

For github pages or code cloud pages, we cannot directly configure Github pages, but we can add a 404 page when committing. The simple solution is as follows:

We create a new project root directory and copy the contents in it completely into the project. Doing this way github pages will still give a 404 response at the right time, the browser will process the page correctly and load our application normally.

Hack on this:S(GH)PA: The Single-Page App Hack for GitHub Pages

3. What is the difference in principle between "#" and "no "#"?

3.1 This requires first talking about what front-end routing is:

In the past, routing was done in the background, and we navigated to the specific html page through the URL requested by the user. Now, we can use Angular, vue, react, etc. to achieve the front-end control of routing jumping through configuration files.

How to implement front-end routing:

  • Implemented through hash When the hash of the url changes, a callback registered by hashchange is triggered (the lower version does not have hashchange event, and it is implemented through reincarnation detection of the url), and different operations are performed in the callback and different contents are displayed.
    If you use hash to implement it, the URI rule should include #, and the content behind # in the route is hash. The anchor point we often say should be strictly a[name] and other elements in the page.
  • HTML5 history API operation browser session history implementation
    The route based on history implementation does not contain #, which is the original route.

3.2 Routing policies in Angular

The routing strategy provided by angular2 is also implemented based on the above two principles. It can be configured through providers or () in @NgModule:

1) There are # in the route

@NgModule({
 imports:[(routes,{useHash:true})]
})

or

@NgModule({
 imports:[(routes)],
 providers:[
  {provide: LocationStrategy, useClass: HashLocationStrategy} 
 ]
})

HashLocationStragegy

Suitable for paths based on anchor markings, such as /#/**, the backend only needs to configure a root route.

2) html5 routing (no #)

Use PathLocationStrategy (the default policy of angular2, that is, HTML5 routing), and the regular path to use this route does not have #. This strategy requires the support of backend configuration, because our application is a single-page application. If the background does not have the correct configuration, when the user jumps from one route to another route or refreshes in the browser, it will return 404, and it needs to cover all routing situations in the server (the backend can be configured through nginx or apache).

@NgModule({
 imports:[(routes)],
 providers:[
 {provide: LocationStrategy, useClass: PathLocationStrategy} 
 // This line is optional because the default LocationStrategy is PathLocationStrategy ]
})

Change the base href attribute, Angular will handle routing jumps through this attribute

<base href="/app/" rel="external nofollow" rel="external nofollow" >

On the backend server, use the following rules to match all page request guidance pages.

we must render the  file for any request coming with below pattern


<!doctype html>
<html>
<head>
 <meta charset="utf-8">
 <title>My App</title>
 <base href="/app/" rel="external nofollow" rel="external nofollow" >
 <body>
 <app-root>Loading...</app-root>
 <script type="text/javascript" src=""></script>
 <script type="text/javascript" src=""></script>
 </body>
</html>

3.3 Pros and cons of front-end routing

advantage:

1. Compared with performance and user experience, backend routing will send a request to the server every time it visits a new page, and then the server will respond to the request. This process will definitely be delayed. When the front-end route accesses a new page, it only changes the path. Without network delay, it will greatly improve the user experience.

2. In some cases, using ajax request can make the page refreshed without refresh. The page changes but the URL does not change. The user cannot get the desired URL address. Using front-end routing to make a single page web page can solve this problem well.

shortcoming:

Using the browser's forward and back button, the request will be resented, and the cache will not be used reasonably.

Summarize

The above is the entire content of this article. I hope that the content of this article has a certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.