8

I'm updating an old website with Angular, and one of the requirements I have to meet is that all routes should remain the same as they were (For SEO purposes).

Many of the old website's routes finish with a slash (Like /my/route/), and some of them finish with a .html, like /my/route.html.

The issue is that routerLink deletes the final slash in every route finishing by a slash (My route is now /my/route).

How can I make routerLink to keep the trailing slash ?

A light example can be seen here : AngularTrailingSlash.

7
  • what do you mean by many of your routes finish by / or .html? What routes are we talking about?
    – YounesM
    Jan 24, 2018 at 14:58
  • The routes of the old website I'm renewing with Angular. I want to have the same routes on the new one (For obvious SEO reasons). Jan 24, 2018 at 15:00
  • Can't you just use 301 redirects?
    – David
    Feb 6, 2018 at 21:59
  • Yes, I could do it, but a 301 redirect will lose some link juice, resulting in SEO loss, and I can't afford it with the amount of pages I'm managing. Feb 6, 2018 at 22:09
  • Since Jul 2016 Google no longer penalize 301 redirect, so maybe you can really consider the 301 way, is way much cleaner that the other options.
    – gmazzotti
    Feb 8, 2018 at 12:20

5 Answers 5

5
+50

I added below to your app.module.ts

import {Location, PathLocationStrategy} from '@angular/common';


const _orig_prepareExternalUrl = PathLocationStrategy.prototype.prepareExternalUrl;

PathLocationStrategy.prototype.prepareExternalUrl = function(internal) {
  const url = _orig_prepareExternalUrl.call(this, internal);

  if (url === '') {
    return url;
  }

  console.log('For ' + internal + ' we generated ' + url);
  if (url.endsWith('.html')) {
      return url;
  }

  if (url.endsWith('/')) {
    return url;
  }


  return url + '/';

};

Location.stripTrailingSlash = function (url) {
    const /** @type {?} */ match = url.match(/#|\?|$/);
    const /** @type {?} */ pathEndIdx = match && match.index || url.length;
    const /** @type {?} */ droppedSlashIdx = pathEndIdx - (url[pathEndIdx - 1] === '/' ? 1 : 0);
    const first = url.slice(0, droppedSlashIdx);
    const last = url.slice(pathEndIdx);

    if (first.endsWith('.html')) {
        return first + last;
    }

    return first + '/' + last;

};

And it now works for me with a trailing slash when .html is not there

9
  • I maybe wrong, but I hadn't any difference when I tried : links generated on the template were still missing the last slash. Feb 7, 2018 at 17:14
  • Okie I didn't look at the generation part rather just browsing the URL part. Will look into it Feb 7, 2018 at 17:39
  • @MarcBrillault, I have a possible fix for the same but I believe your project has some error. When I click link I get Error: Uncaught (in promise): TypeError: Cannot read property 'component' of null. Can you fix that in your git repo first? Feb 7, 2018 at 20:02
  • @MarcBrillault, I have added the changes. The url are now fine but your navigation issue is still there Feb 8, 2018 at 3:08
  • I'm very sorry for the delay. Your answer works, thank you ! Feb 13, 2018 at 9:22
2

Even more improved code (based on code from Umesh).

Add on top of main.ts:

import { Location } from "@angular/common";
// Prevent stripping of trailing slash
Location.stripTrailingSlash = function stripTrailingSlashNew(url: string) {
  return url;
};
2

Below code worked for me:

export const contactUsRoutes: Routes = [
    {
        path: 'contact-us/.', component: ContactUsComponent
    }
];

. .

<a [routerLink]="['/contact-us/.']">Contact us</a>

And add below code in your main.ts:

import { Location } from '@angular/common';

const __stripTrailingSlash = (Location as any).stripTrailingSlash;
(Location as any).stripTrailingSlash = function _stripTrailingSlash(url: string): string {
  const queryString$ = url.match(/([^?]*)?(.*)/);
  if (queryString$[2].length > 0) {
    return /[^\/]\/$/.test(queryString$[1]) ? queryString$[1] + '.' + queryString$[2] : __stripTrailingSlash(url);
  }
  return /[^\/]\/$/.test(url) ? url + '.' : __stripTrailingSlash(url);
};

I have referred below link for this solution:

https://stackblitz.com/github/ssatz/Angular5-Preserve-Trailing-Slash

1
  • If I have to preserve slashes in the middle of URL then any possibilities? Sep 30, 2019 at 14:15
0

Add this code in the main.ts file to keep trailing slash in the routerLink.

import { Location } from '@angular/common';
const __stripTrailingSlash = (Location as any).stripTrailingSlash;
(Location as any).stripTrailingSlash = function _stripTrailingSlash(url: string): string {
  return /[^\/]\/$/.test(url) ? url : __stripTrailingSlash(url);
}

// import main ng module
// bootstrap on document ready
2
  • Why Location as any?
    – edwin
    Sep 19, 2018 at 11:52
  • 1
    This code does not work with url parameters like path/?params.
    – edwin
    Sep 19, 2018 at 14:23
0

Try with Location class extends in AppModule like this:

app.module.ts:

import { Injectable } from '@angular/core';
import { Location } from '@angular/common';

@Injectable()
export class UnstripTrailingSlashLocation extends Location {
  public static stripTrailingSlash(url: string): string {
    return url;
  }
}
Location.stripTrailingSlash = UnstripTrailingSlashLocation.stripTrailingSlash;

@NgModule({
            ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.