php 在Linux中使用反向代理运行Symfony 5

2fjabf4q  于 2023-11-16  发布在  PHP
关注(0)|答案(3)|浏览(103)

我喜欢在反向代理后面运行Symfony 5应用程序,该代理提供以下端点:
https://my.domain/service1/
代理配置基本上是这样的:

ProxyPass /marketsy/ http://internal.service1/

字符串
在反向代理连接到的服务器上,我使用以下apache规则来服务我的Symfony应用程序:

<VirtualHost *:80>
  ServerName internal.service1
  DocumentRoot /webroot/service1/public

 <FilesMatch \.php$>
     SetHandler proxy:unix:/run/php/php7.2-fpm-ui.sock|fcgi://localhost
     SetEnvIfNoCase ^Authorization$ "(.+)" HTTP_AUTHORIZATION=$1
     SetEnv HTTP_X_FORWARDED_PROTO "https"
 </FilesMatch>

 <Directory  /webroot/service1/public>
     AllowOverride None
     Require all granted
     FallbackResource /index.php
 </Directory>

 <Directory  /webroot/service1/public/bundles>
     FallbackResource disabled
 </Directory>
</VirtualHost>


应用程序本身是可重访问的,但Symfony无法处理“service1”路径前缀。
例如,它试图访问https://my.domain/_wdt/8e3926而不是https://my.domain/service1/_wdt/8e3926下的分析器,并且在根路由旁边,所有路由都不起作用:
例如:当我尝试访问https://my.domain/service1/my/page时,我将被重定向到https://my.domain/my/page
现在我的问题是,我如何配置Symfony知道“service1”路径前缀时,生成的网址ets。

wgmfuz8q

wgmfuz8q1#

正确的做法(示例):
创建src/Controller/BarController.php

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;

class BarController
{
    public function index()
    {
        return new Response('<p>Bar controler response</p>');
    }
}

字符串
src/Controller/FooController.php

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;

class FooController
{
    public function index()
    {
        return new Response('<p>Foo controler response</p>');
    }
}


创建config/routes/prefix-routes.yaml

index:
    path: /
    controller: App\Controller\DefaultController::index

bar:
    path: /bar
    controller: App\Controller\BarController::index
 
foo:
    path: /foo
    controller: App\Controller\FooController::index


并编辑路由config/routes.yaml-删除其内容,只需放入:

prefixed:
   resource: "routes/prefix-routes.yaml"
   prefix: service1


所有的控制器现在都可以在url上使用:

http://localhost/service1/ for DefaultController.php
http://localhost/service1/bar for BarController.php
http://localhost/service1/foo for FooController.php


如果你想让你的分析器也使用service1前缀,那么可以这样编辑config/routes/dev/web_profiler.yaml

web_profiler_wdt:
    resource: '@WebProfilerBundle/Resources/config/routing/wdt.xml'
    prefix: service1/_wdt

web_profiler_profiler:
    resource: '@WebProfilerBundle/Resources/config/routing/profiler.xml'
    prefix: service1/_profiler


现可于下列地点索取:

http://localhost/service1/_wdt... for wdt
http://localhost/service1/_profiler for profiler


为注解添加前缀:
创建控制器src/Controller/AnnoController.php

<?php

namespace App\Controller;

use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;

class AnnoController extends AbstractController
{
    /**
     * @Route("/anno", name="anno")
     */
    public function index()
    {
        return new Response('<p>Anno controler response</p>');
    }
}


编辑config/routes/annotations.yaml并添加prefix: service1

controllers:
    resource: ../../src/Controller/
    type: annotation
    prefix: service1

kernel:
    resource: ../../src/Kernel.php
    type: annotation


现在前缀被添加到通过注解完成的路由中:

http://localhost/service1/anno for AnnoController.php


一些参考资料:
Symfony路由前缀
Symfony Routing Configuration Keys

添加前缀快速和肮脏的解决方法,将前缀service1添加到所有路由(不推荐)。

而不是像上面那样更改路由,只需编辑src/Kernel.phpprotected function configureRoutes
并通过在末尾添加->prefix('service1')来更改每一个$routes->import行,因此它看起来是这样的:

protected function configureRoutes(RoutingConfigurator $routes): void
{
    $routes->import('../config/{routes}/'.$this->environment.'/*.yaml')->prefix('service1');
    $routes->import('../config/{routes}/*.yaml')->prefix('service1');

    if (is_file(\dirname(__DIR__).'/config/routes.yaml')) {

        $routes->import('../config/{routes}.yaml')->prefix('service1');

    } elseif (is_file($path = \dirname(__DIR__).'/config/routes.php')) {
        (require $path)($routes->withPath($path), $this);
    }
}


所有的控制器现在都可以在url上使用:

http://localhost/service1/ for DefaultController.php
http://localhost/service1/bar for BarController.php
http://localhost/service1/foo for FooController.php


以及分析器:

http://localhost/service1/_wdt... for wdt
http://localhost/service1/_profiler for profiler

k3fezbri

k3fezbri2#

除了@Jimmix提供的解决方案之外,我还必须编写一个订阅者来为我的请求路径添加前缀:

<?php namespace My\Bundle\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class AppPrefixSubscriber implements EventSubscriberInterface {

    /** @var string */
    private $appPrefix;

    public function __construct(?string $appPrefix) {
        $this->appPrefix = $appPrefix;
    }

    /**
     * Returns events to subscribe to
     *
     * @return array
     */
    public static function getSubscribedEvents() {
        return [
            KernelEvents::REQUEST => [
                ['onKernelRequest', 3000]
            ]
        ];
    }

    /**
     * Adds base url to request based on environment var
     *
     * @param RequestEvent $event
     */
    public function onKernelRequest(RequestEvent $event) {
        if (!$event->isMasterRequest()) {
            return;
        }

        if ($this->appPrefix) {
            $request = $event->getRequest();

            $newUri =
                $this->appPrefix .
                $request->server->get('REQUEST_URI');

            $event->getRequest()->server->set('REQUEST_URI', $newUri);
            $request->initialize(
                $request->query->all(),
                $request->request->all(),
                $request->attributes->all(),
                $request->cookies->all(),
                $request->files->all(),
                $request->server->all(),
                $request->getContent()
            );
        }
    }

}

字符串

vuktfyat

vuktfyat3#

从Symfony 5.3开始,不需要事件订阅者手动修改请求路径或更改路由前缀,因为symfony现在支持X-Forwarded-Prefix HTTP头。当反向代理将此头传递给symfony应用程序时,Request对象的基本URL将被正确设置,并且所有生成的路径都会自动添加前缀。
在apache中,你可以使用mod_header来添加header,方法是在vhost配置中添加一个RequestHeader set X-Forwarded-Prefix "/marketsys"(或类似)指令。
如果您想使用此功能,请确保将X-Forwared-Prefix配置为可信头。

相关问题