Generate relative-path URLs with Slim Router

The Slim Router (same as FastRoute?) seems to support routes only with leading slash (e.g. /home).

This is fine when the app is directly accessible at a domain (e.g. http://localhost/home, https://mysite.com/home) but it provokes cumbersome problems when serving the app at a sub-path of a domain (e.g. http://localhost/myapp/home, https://mysite.com/myapp2/home).

This limits the possibilities, forcing the app to always generate absolute-path references (e.g. /myapp2/home, by configuring basePath = "/myapp2"), instead of allowing to use the simpler relative-path references (e.g. home).

For my app I want to generate relative-path URIs instead.
When /myapp2/home page is loaded in the browser, then a link to the About-page should be generated as href="about" instead of href="/about", because:

  • about will load relatively to /myapp2/home, correctly leading to /myapp2/about.
  • /about will load relatively to the host root path /, wrongly leading to /about (that is outside of the namespace of my app!).

I’d rather specify a base tag with href="myapp2/" (or, better, no base-tag at all), rather than configuring $app->setBasePath("myapp2") (and resolving server-side what the basepath value must be).

How can this be achieved with Slim 4 Router?

Why don’t you use a virtual host for that use case ?

What do you suggest exactly with vhosts?
How can they help me here, with the mount of the app at a sub-path?
Does a virtual-host cause the RouteParser to correctly generate relative-path references/routes? (that consider the sub-path specified by the virtual-host)

Either when using setBasePath or not, the router will regardless generate absolute-path routes with a leading slash :dotted_line_face:

Probably relativeUrlFor was intended instead for relative-path references.
But this method doesn’t keep virtual-host root path in consideration, won’t be affected at all by setBasePath, and isn’t aware of route context (calling relativeUrlFor from /collection/add route will generate a link collection/add that will go to /collection/collection/add :grimacing: .

Does virtualhost mean only <VirtualHost> directive, or it also include <Location>|<Directory directive? (because I’m using them, but they don’t affect the basePath).

I was just asking why use subpaths http://localhost/myapp/home http://localhost/myapp2/home

when you can have 2 vhosts : http://myapp/home and http://myapp2/home

With your etc/hosts correctly set

127.0.0.1 myapp
127.0.0.1 myapp2

Thanks for the suggestions.
Unfortunately I cannot use 2 vhosts: I have no influence on the main domain and server.
The app necessarily has to be exposed at a sub-path (1 level deep; but I have other apps that are exposed 2-level deep, like /portal-namespace/specific-app/home), that’s why I’m looking for solutions to it.