I have a multi-language setup with two languages. I also use custom routes.
Some of these routes shall be available only without language code in the URL since they are language independent and wouldn’t make sense to be served under different language URLs. This works out of the box if I leave out the language pattern in the route defintion:
And some shall be available only with language code in the URL. That’s how Kirby’s regular routes are handled in a multi-language setup: if the language code is missing, redirect to the default (or detected) language. But my custom routes now are available with or without language code in the URL:
Is there a way of using Kirby’s built-in redirection if there is no language code, or do I need to take care of that on my own?
The problem is: I would have thought that $language would be undefined without a language code in the URL, but it’s actually set to the ‘current language’. So Kirby already took care of fixing the missing $language, but not of redirecting.
The fact that Kirby redirects regular page routes in a multi-language setup when the language code is missing. So /some-page will be redirected to /en/some-page (if en is the default or detected language).
That’s exactly what I thought but it’s not true. The passed $language variable will be populated with the ‘current language’ determined by Kirby (which would be the detected or default language I guess). That fact also makes it hard to detect if the language code is missing from the URL, because I can’t simply use something like if ($language === undefined) redirect().
But it’s perfectly normal to have redirection rules in a CMS to make sure a certain route pattern is kept.
(By the way, I’m using Kirby as a headless CMS here. The sitemap route returns a sitemap, which doesn’t have a language, and the layout route returns the navigation elements etc. in the current language. Also, this is in no way critical, it could only cause confusion if I forget to add a language code to a layout request URL and am wondering which language the response is coming back in. I just would have thought that Kirby automatically returned an error or a redirect if I try to access a route that has explicitly been set up to use a language, without a language.)
Right, this happens if you have no routes that intercept the Kirby’s default routing.
$language should always be the default language, if not present the route you call.
Well, yes, but as I said above, if you use the router you want to react to a given pattern (and your pattern may intercept the usual flow of things). Like when you call a route like layout without the language pattern, Kirby would by default reroute this to defaultlanguagecode/layout and if such a page does not exist, redirect to the error page. But again, you intercept the flow of things.
Note that you can also call your route patterns using the language code in the pattern…