Symfony 子域路由 [英] Symfony sub domain routing

查看:57
本文介绍了Symfony 子域路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何使用子域访问 Symfony 中的子文件夹.

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/*

一些详细的例子:

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")

但是我还没有找到隐藏子文件夹的方法.因此,要访问个人资料页面,您仍然需要转到 app.example.com/app/profile.这违背了子域在 url 中包含/app 的目的.

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.

是的,显然任何子域都会在整个应用程序中限制子文件夹.所以你不能有 example.com/api/因为那将被保留给 api.example.com

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

推荐答案

此解决方案将拦截 REQUEST_URI 并将子域添加为尚未使用的根文件夹.

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

意思是 app.example.com 和 app.example.com/app 将访问同一个页面.

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'];
}

这样做的好处是可以将所有控制器放在文件夹中.如果您有多个配置文件控制器,它们都可以从/profile 访问,但位于不同的子域下.

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.

这篇关于Symfony 子域路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆