Php 如何强制产品使用https,而开发环境使用http?
我有一个symfony2应用程序 在prod服务器上,我希望所有路由都通过https,而在dev中,我希望能够使用http。仅使用symfony2如何实现这一点?我不想接触Web服务器配置 我尝试在我的Php 如何强制产品使用https,而开发环境使用http?,php,symfony,https,routing,Php,Symfony,Https,Routing,我有一个symfony2应用程序 在prod服务器上,我希望所有路由都通过https,而在dev中,我希望能够使用http。仅使用symfony2如何实现这一点?我不想接触Web服务器配置 我尝试在我的routing.yml myBundle: resource: "@MyBundle/Controller/" type: annotation prefix: / schemes: [https] 在myrouting_dev.yml中包含此项时:
routing.yml
myBundle:
resource: "@MyBundle/Controller/"
type: annotation
prefix: /
schemes: [https]
在myrouting_dev.yml中包含此项时:
myBundle:
resource: "@MyBundle/Controller/"
type: annotation
prefix: /
schemes: [http]
_main:
resource: routing.yml
parameters:
httpProtocol: https
即使在开发模式下,它仍然希望使用https。我认为您可以在app\u dev.php
文件中检查该方案,并根据该方案将其重定向到https
$url = parse_url($_SERVER['HTTP_REFERER']);
if ($url['scheme'] == 'http') {
header("Location: https://{$_SERVER['SERVER_NAME']}{$_SERVER['PHP_SELF']}");
}
或者可以在.htaccess
中为URL中的app_dev.php
应用一些更改,您可以为此定义参数。在app/config/config.yml中定义:
parameters:
httpProtocol: http
然后在app/config/config_prod.yml
中:
myBundle:
resource: "@MyBundle/Controller/"
type: annotation
prefix: /
schemes: [http]
_main:
resource: routing.yml
parameters:
httpProtocol: https
并在routing.yml
中更改为:
myBundle:
resource: "@MyBundle/Controller/"
type: annotation
prefix: /
schemes: ['%httpProtocol%']
清除缓存(prod和dev)应该可以工作。我的第一个解决方案工作正常,但是应该注意不要在路由\u dev.yml
中覆盖自己的路由。在文件的末尾,我
_main:
resource: routing.yml
所以我所有的包路由都改回了https方案。对条目进行排序,使我的自定义条目位于最后解决了问题。更改app.php的最后几行,如下所示:
if ($request->getScheme() === 'http') {
$urlRedirect = str_replace($request->getScheme(), 'https', $request->getUri());
$response = new RedirectResponse($urlRedirect);
} else {
$response = $kernel->handle($request);
}
$response->send();
$kernel->terminate($request, $response);
唉,这是不可能的,因为在prod上,http端口被阻止了,所以我无法从那里进行任何重定向,这也是我不想依赖服务器端配置,而是在symfony2配置中实现它的原因。我以为您只想在开发模式下这样做,如果http端口被阻止,prod可以同时使用http和httpsIf,请求如何到达apache,更不用说symfony可能是我在resource:@MyBundle/Resources/config/routing.yml“
下的app/config/routing.yml中尝试设置schemes:[https]
的副本,但它不起作用(它不会对我的bundle中定义的路由强制使用https)。你有没有尝试过像你在routes中建议的那样不使用类型:注解
?这是个好主意!它还可用于配置security.yml
。对于希望在注释中逐案使用此方法的任何人,如下所示:@Route(“/register.html”,schemes={“%httpProtocol%”)值得一提的是,如果你也使用了fos_用户路由,你也需要将schemes设置添加到fos_用户路由中。我不想在app.php
中硬编码模式,我更喜欢在配置文件中设置这样的设置,以便轻松更改设置。在http内核运行之前,你没有任何配置文件!这并不完全正确。请看被接受的答案,以及我如何让它为我工作的答案。那里没有必要对app.php进行任何更改。你提供了一个有效的解决方案,但我不推荐任何一个。