Setting index route in Symfony 2

2019-03-02 23:13发布

问题:

I've got Symfony2 installed, and a mostly working site, the only issue is I don't know how to set a default route. Currently, I access my index and other routes with the following URLs:

www.example.com/app_dev.php/index

www.example.com/app_dev.php/example_route

I'd like to have www.example.com default to the index route, so I can get the same results with the following URLs:

www.example.com

www.example.com/example_route

I'm running lighttpd as my web server. How can I configure lighttpd/Symfony2 to do this?

回答1:

Just create a route that maps to the / pattern :

# app/config/routing.yml
homepage:
    pattern:   /
    defaults:  { _controller: AcmeHomeBundle:home:show }

This will route to whatever controller you specify.



回答2:

Great Docs:

How to Configure a Redirect without a custom Controller

Routing



回答3:

I used below code to set home page route.It's working fine

Symfony version : Symfony 3.2.8

homepage:
    path:   /
    defaults:  { _controller: AppBundle:Home:index}


回答4:

For me Symfony 4.1.x

Edit the file

# app/config/routes.yaml
index:
    path: /
    controller: App\Controller\YourIndexController::yourIndexFunction

There's App\Controller is the namespace you declare at the start of the Controller class, and after is your class name and method name to route to.



回答5:

I solved this problem by just removing the following from routing_dev.yml

_welcome:
    pattern:  /
    defaults: { _controller: AcmeDemoBundle:Welcome:index }

That is assuming you have setup a default / route in a routing.yml file or by defining the route in a controller like:

/**
 * @Route("/")
 * @Template()
 */
public function indexAction()
{
    return array('name' => '1');
}


回答6:

The answer given by ManseUK is very much helpful but I have little elaboration

1)

# app/config/routing.yml
homepage:
    pattern:   /
    defaults:  { _controller: AcmeHomeBundle:home:show }

2) rename the app_dev.php to index.php and this will route to the home page automatically