1

I'm looking to create a "subdomain" path to my custom controller running on a Drupal 8 site, with routing and hopefully without the need for an additional module.

The idea is to for example have a route like account.example.com or dev.example.com point to a custom controller I've made in my module. Or a path like api.example.com for external REST queries.

All the documentation describe just the traditional example.com/path methods, and googling resulted to nothing, but the domain module, which seems excessive and maybe for a different purpose even.

What I wish to achieve is not a separate installation sharing the content, but just a path to my controller that is domain-specific, like the i18n module is able to provide the language parameter as subdomain or path prefix.

1

If you want to set a controller for subdomain you just create a subdomain and handle it by DNS and web server, then set your subdomain path as root path for the subdomain on your web server, I mean both main domain and subdomain will be the same. As you said, you can create a route/controller for them (because the code and modules are the same, so routes will be available on both).

If you don't want the subdomains available on your main domain, on your handler check the domain name; if a request comes from the main domain, don't return the result for it. (Redirecting it to the homepage could be an idea.)

But the power of Symfony shows itself to us: Instead of manually handling the domain and subdomain filtering on the route, use host in the route definition.

   host: "dev.example.com"

Take a look at How to Match a Route Based on the Host for further help about using that directive.

| improve this answer | |
  • I was hoping there'd be a more dynamic way of doing this also, without specifying actual subdomains with the DNS - possibly utilizing the method internationalization's url language detection uses, so in the future I could create subdomains dynamically for event's – Alari Truuts Mar 29 '17 at 11:27
  • You don't need to use static domains with host: See the example using {project_name}.example.com, which is not the same as project_name.example.com. – kiamlaluno Mar 29 '17 at 11:45
  • @AlariTruuts Drupal Couldn't handle localization subdomain by itself, you should first create your subdomain on your DNS Zone ( or in your apache or nginx config files). – Yuseferi Mar 29 '17 at 11:57
  • @kiamlaluno yeah, he can use dynamic route, but it requires to specify his subdomains on DNS before. – Yuseferi Mar 29 '17 at 11:58
  • @zhilevan Apparently there are wildcard * domain names I can set so great, I guess I have my solution :) – Alari Truuts Mar 29 '17 at 12:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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