Hugo

Links without a trailing slash - a solution

Here is how I got URLs like “/contact” instead of “/contact/” on my site.

I use Cloudfront CDN (origin pull) and my origin server is apache + nginx (VestaCP)

  1. In my templates, I use the “substr” function to remove the last character in links (ie in menus)
  2. I make my origin server serve the index.html file when a directory (no trailing slash) is requested. I also make it redirect trailing-slash URLs to no-trailing-slash URLs (a 404 could also be considered)

Altering the links created by Hugo

When printing a link URL in the template, instead of inserting ie {{ .URL }}, I insert: {{substr .URL 0 -1}}. This simply cuts of the last character, which with prettyUrls is always a slash.

Instructing the server to serve without trailing slashes

I have put this in my .htaccess:
If you run only nginx, there is a solution available here

# Enforce no-trailing-slash policy.
# That is, if we have a file located at "/contact/index.htm",
# it will be available at this url: "/contact" (no trailing slash)
# Also, trailing-slash will redirect to non-trailing slash URL.
# In our case, this url: "/contact/" will redirect to this: "/contact"

# Disable automatic directory slashing
DirectorySlash Off

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

# Redirect trailing-slash URLs to non-trailing-slash URL
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)/$ $1 [L,R=301] # <- for test, for prod use [L,R=301]

# Let non-trailing slash URLs return the content of index.html
# - but only do this when its a directory.
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)$ %{REQUEST_URI}/index.html [L] # <- for test, for prod use [L,R=301]

</IfModule>

When developing locally, using hugo server, links still works, because hugo server automatically redirects ie “/contact” to “/contact/”.

Sitemap

There is also the sitemap.xml to consider. - Ideally you want it to display the correct links (though unalterered links still works - by redirection). I simply disabled sitemap generation by putting this line in config.toml:

disableSitemap = true
```. 
Its my impression that sitemap.xml isn't that important. Also, my site is multilanguage, and hugo currently does not connect the versions in sitemap.xml (I have created an issue [here](https://github.com/spf13/hugo/issues/3467))

## CDN
If you use a CDN, it must be able to handle URL's like "/contact". I guess it is standard functionality, but I've only tried it on Cloudfront. I'm using origin pull (origin push is not available on Cloudfront). I guess it will not be possible to set up URLs without trailing slash with origin push

## Hugo support for URLs without a trailing slash?
Join the discussion [here](https://discuss.gohugo.io/t/hugo-support-for-urls-without-a-trailing-slash/6763)
4 Likes