правильно настроить маршрутизацию в Symfony, чтобы иметь правильный URL и маршрут

0

Я использую Symfony 2.5 (последняя версия) для создания веб-приложения. Я работаю с локальным сервером WAMP на Windows 7.

Когда я приветствую приложение, это URL-адрес, я получаю http://localhost/Symfony/web/. На самом деле я хотел бы добавить /домашнюю страницу.

У меня есть первый комплект с именем WelcomeBundle с его контроллером: он касается моей главной страницы приложения: Gir/WelcomeBundle/Controller/HomePageController.php

<?php

namespace Gir\WelcomeBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class HomePageController extends Controller
{
    public function indexAction()
    {
        return $this->render('GirWelcomeBundle:HomePage:index.html.twig');
    }
}

Это файл маршрутизации: Gir/WelcomeBundle/Ressource/config/routing.yml

GirWelcomeBundle_HomePage:
  pattern:  /
  defaults: { _controller: GirWelcomeBundle:HomePage:index }
  requirements:
    methods: GET
    schemes:  https

И это общий файл маршрутизации: app/config/routing.yml

GirWelcomeBundle:
    resource: "@GirWelcomeBundle/Resources/config/routing.yml"
    prefix:   /

gir_administration:
    resource: "@GirAdministrationBundle/Resources/config/routing.yml"
    prefix:   /

fos_user:
    resource: "@FOSUserBundle/Resources/config/routing/all.xml"

gir_user:
    resource: "@GirUserBundle/Resources/config/routing.yml"
    prefix:   /

Поэтому, когда я прихожу первым в приложении, у меня есть HomePage, поэтому он отлично работает. Это URL-адрес, когда я приветствую приложение: http://localhost/Symfony/web/

Но если я хочу добавить такой путь (я добавляю /домашнюю страницу в строке пути): Gir/WelcomeBundle/Ressource/config/routing.yml

GirWelcomeBundle_HomePage:
  pattern:  /homepage
  defaults: { _controller: GirWelcomeBundle:HomePage:index }
  requirements:
    methods: GET
    schemes:  https

Приложение не находит маршрут, у меня есть эта ошибка:

No route found for "GET /" (from "http://localhost/Symfony/")
404 Not Found - NotFoundHttpException
1 linked Exception: ResourceNotFoundException »

Кто-то знает почему?

Затем, когда я пытаюсь оценить страницу администрирования, браузер показывает мне, что страница является недоступной веб-страницей, подобной этой.

Я не совсем понимаю. Пакет называется AdministrationBundle, это код контроллера: Gir/AdministrationBundle/Controller/AdministrationController.php

<?php

namespace Gir\AdministrationBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class AdministrationController extends Controller
{
    public function indexAction()
    {
        return $this->render('GirAdministrationBundle:Admin:index.html.twig');
    }
}

И это файл маршрутизации: Gir/AdministrationBundle/Ressource/config/routing.yml

gir_administration_homepage:
    pattern:  /administration
    defaults: { _controller: GirAdministrationBundle:Administration:index }
    requirements:
    methods: GET
    schemes:  https

Кто-то может мне помочь и объяснить, почему?

Обновить сообщение: это.htacess в веб-папке

DirectoryIndex app.php

<IfModule mod_rewrite.c>
    RewriteEngine On


    # Determine the RewriteBase automatically and set it as environment variable.
    # If you are using Apache aliases to do mass virtual hosting or installed the
    # project in a subdirectory, the base path will be prepended to allow proper
    # resolution of the app.php file and to redirect to the correct URI. It will
    # work in environments without path prefix as well, providing a safe, one-size
    # fits all solution. But as you do not need it in this case, you can comment
    # the following 2 lines to eliminate the overhead.
    RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
    RewriteRule ^(.*) - [E=BASE:%1]

    # Sets the HTTP_AUTHORIZATION header removed by apache
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ app_dev.php [QSA,L]

    # Redirect to URI without front controller to prevent duplicate content
    # (with and without '/app.php'). Only do this redirect on the initial
    # rewrite by Apache and not on subsequent cycles. Otherwise we would get an
    # endless redirect loop (request -> rewrite to front controller ->
    # redirect -> request -> ...).
    # So in case you get a "too many redirects" error or you always get redirected
    # to the start page because your Apache does not expose the REDIRECT_STATUS
    # environment variable, you have 2 choices:
    # - disable this feature by commenting the following 2 lines or
    # - use Apache >= 2.3.9 and replace all L flags by END flags and remove the
    #   following RewriteCond (best solution)
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteRule ^app\.php(/(.*)|$) %{ENV:BASE}/$2 [R=301,L]

    # If the requested filename exists, simply serve it.
    # We only want to let Apache serve files and not directories.
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule .? - [L]

    # Rewrite all other queries to the front controller.
    RewriteRule .? %{ENV:BASE}/app.php [L]
</IfModule>

<IfModule !mod_rewrite.c>
    <IfModule mod_alias.c>
        # When mod_rewrite is not available, we instruct a temporary redirect of
        # the start page to the front controller explicitly so that the website
        # and the generated links can still be used.
        RedirectMatch 302 ^/$ /app.php/
        # RedirectTemp cannot be used instead
    </IfModule>
</IfModule>
  • 0
    Вы правильно настроили виртуальный хост? Например, DocumentRoot /var/www/gir.dev/web Также включен ли mod_rewrite с правильным .htaccess?
  • 0
    Я обновил свой пост, и поэтому вы можете увидеть мой код htaccess.
Показать ещё 2 комментария
Теги:
.htaccess
url
routing

2 ответа

1

По вашему описанию, я думаю, ваш routing.yml выглядел примерно так:

GirWelcomeBundle_HomePage:
    pattern:  /
    defaults: { _controller: GirWelcomeBundle:HomePage:index }
    requirements:
        methods: GET
        schemes:  https

GirWelcomeBundle_HomePage:
    pattern:  /homepage
    defaults: { _controller: GirWelcomeBundle:HomePage:index }
    requirements:
        methods: GET
        schemes:  https

Проблема с этим подходом заключается в том, что ваш GirWelcomeBundle_HomePage. Решение прост: GirWelcomeBundle_Root маршрутов по-разному, например: GirWelcomeBundle_Root и GirWelcomeBundle_Home.

Также жизнеспособная душа должна была бы просто определить ее по одному маршруту:

GirWelcomeBundle_HomePage:
    pattern:  /{homepage}
    defaults: { _controller: GirWelcomeBundle:HomePage:index, homepage: 'homepage' }
    requirements:
        methods: GET
        schemes:  https
  • 0
    Это та же проблема. Я изменяю свой код, как вы предлагаете мне, но он все еще не работает.
  • 1
    @Julien Вы в среде разработчиков? Если нет, очистите кеш. php app/console ca:c --env=prod
Показать ещё 1 комментарий
0

Измените свой маршрут на /главную страницу, проверьте php app/console router:debug -output, и вы увидите, что нет пути для/но одного для/главной страницы.

Поэтому вам нужна другая пара контроллеров/маршрутов для перенаправления с/на/домашнюю страницу.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню