-3

How can we use sub domains to access sub folders in Symfony.

The question is, how can I have a sub domain routed to a folder?

example.com         -> example.com/*
app.example.com     -> example.com/app/*
admin.example.com   -> example.com/admin/*
api.example.com     -> example.com/api/*

Some detailed examples:

url requested           controller called           route name
----------------------------------------------------------------
example.com/            example.com/                main_home
example.com/login       example.com/login           main_login

app.example.com/        example.com/app/            app_home
app.example.com/profile example.com/app/profile     app_profile

So far hard coding each controller works

Symfony: @Route("/", name="app_home", host="example.com")
Symfony: @Route("/", name="sub1_home", host="sub1.example.com")

But I haven't found a way of hiding the sub folder. So to access the profile page you still need to go to app.example.com/app/profile. Which defeats the purpose of the subdomain having /app in the url.

And yes, obviously any subdomain would have the sub folders restricted in the whole app. So you couldn't have example.com/api/ because that would be reserved for api.example.com

Bradmage
  • 1,233
  • 1
  • 15
  • 41

2 Answers2

1

@Bradmage why do you complicate what doesn't need to be complicated ? Having

app.example.com     -> example.com/app/*
admin.example.com   -> example.com/admin/*
api.example.com     -> example.com/api/*

will thriple the authorization url because You will need to add login route for each etc. and probably the other things also.

Why don't You leave that and point every subdomain to You application (or strict ones) and rely on a user roles ?

Also You can check up access_control in symfony and host parameter: https://symfony.com/doc/current/security/access_control.html

michal
  • 428
  • 4
  • 14
  • Thanks for that, I think I was over thinking it a bit. access_control { path: '^/admin', roles: ROLE_USER_ADMIN, host: admin.example\.com$ } which also solves some of my other questions too. – Bradmage Apr 06 '21 at 22:48
0

This solution will intercept the REQUEST_URI and add the subdomain as a root folder if not already used.

Meaning app.example.com and app.example.com/app will both access the same page.

if(substr($_SERVER['HTTP_HOST'], 0, strlen('app.')) === 'app.'
    && substr($_SERVER['REQUEST_URI'], 0, strlen('/app')) !== '/app')
{
    $_SERVER['REQUEST_URI'] = '/app'.$_SERVER['REQUEST_URI'];
}

The benefit of this is being able to put all your controllers in folders. If you had a multiple profile controllers, they could both be accessed from /profile but under different sub domains.

E_net4
  • 27,810
  • 13
  • 101
  • 139
Bradmage
  • 1,233
  • 1
  • 15
  • 41