Cms: A site's root URL always has a trailing slash, regardless of `addTrailingSlashesToUrls`

Created on 18 Feb 2020  路  6Comments  路  Source: craftcms/cms

Steps to reproduce

  1. Set the general config option addTrailingSlashesToUrls to false (or just don't set it, as it's the default)
  2. Write the following in a template: {{ siteUrl() }}
  3. Render that template from a site that has a base URL that ends with a path, like https://example.com/en

Expected result: https://example.com/en
Actual result: https://example.com/en/

Additional info

  • Craft version: 3.4.5
  • PHP version: 7.3.13
  • Database driver & version: MySQL 5.5.5
bug minor

All 6 comments

@benface This isn't Craft CMS's related solution but you could solve it with web server. I use NGINX and all trailing slashes at the end of URI that web server match rewrites and friendly 301 redirects it to URI with no trailing slash.

server {
    rewrite /(.*)/$ /$1 permanent;
}

Your actual result: https://example.com/en/
After using rewrite: https://example.com/en

As this minor bug is coming from Craft CMS than it'd solved.

@dominikkrulak Thank you. Yes, I know and already do this. The issue is that following a link to the home page causes a 301 redirect (so two requests instead of one), since the original link from Craft contains a trailing slash, and the web server redirects to the no-trailing-slash URL.

Unfortunately this is going to have to wait until 4.0, because it would end up breaking a lot of templates that currently do things like:

<link rel="stylesheet" type="text/css" href="{{ siteUrl }}assets/style.css">

That assumes that siteUrl will always end in a slash.

Ah yeah, I see. No problem at all.

Also, while this is definitely a bit awkward for site URLs that include a URI segment (e.g. http://example.com/en), the current behavior makes sense for base URLs without one (e.g. http://example.com/) 鈥撀燼s browsers will end up redirecting to http://example.com/ even if you go to http://example.com (no slash). That鈥檚 not immediately obvious by looking at the address bar, but try going to github.com and outputting document.location.href in your browser console 鈥撀爄t will output https://github.com/.

If use SEOmatic and you're looking for a temporary work-around for this issue, this is how I solved it for our sites temporarily until the fix comes out:

{% set currentUrl = currentSite.handle == 'english' ? entry.url : entry.url|trim('/', 'right') %}
{% do seomatic.meta.canonicalUrl(currentUrl) %}

For our sites, this gives us:

It's definitely not hack-free, but it works nicely and it's only one extra line of code in my template.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

lukebailey picture lukebailey  路  3Comments

angrybrad picture angrybrad  路  3Comments

darylknight picture darylknight  路  3Comments

angrybrad picture angrybrad  路  3Comments

bitboxfw picture bitboxfw  路  3Comments