How to redirect every HTTP request to HTTPS in Silex?

1

In Silex, is there any possibility of making a filter that redirects a url to https when it does not have https?

I know how to do this in Laravel, but I would like to do the same with Silex.

For example, when I access the url http://www.exemplo.com , I'd like it redirected to https://www.exemplo.com .

How do I do this in Silex?

    
asked by anonymous 09.03.2017 / 17:20

1 answer

2

According to this answer in SOEN

I think it's like this:

$app = new Silex\Application();

$app['controllers']->requireHttps();

$app->get('/', function () use ($app) {
    return 'Olá mundo!';
});

$app->run();

Documentation on Silex\Controller::requireHttps

  

Note:

     

Wallace left a hint, if you are in HTTPS development environment you may not need it, then you can detect if the script is in debug mode, like this:

     
$app = new Silex\Application();

if (!$app['debug']) {
   $app['controllers']->requireHttps();
}
     

Or for simplicity like this:

     
$app = new Silex\Application();

$app['debug'] || $app['controllers']->requireHttps();

You can also set this by .htaccess as explained in:

Example:

# Redireciona para o HTTPS independente do domínio
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Adiciona www. no prefixo do domínio
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    
09.03.2017 / 17:56