Skip to content

Instantly share code, notes, and snippets.

@ctala
Created September 18, 2020 21:05
Show Gist options
  • Save ctala/fa7d44c9d0f1049d9bbf5507f3b58e87 to your computer and use it in GitHub Desktop.
Save ctala/fa7d44c9d0f1049d9bbf5507f3b58e87 to your computer and use it in GitHub Desktop.
Yii2 Modfied Web Application to Redirect to Https under a Load Balancer provided by AWS.
<?php
namespace common\components;
use Yii;
use yii\web\Application;
/**
* Reescribo para siempre usar HTTPS si es que la url no es segura
* Class MyWebApplication
* @package common\components
*/
class MyWebApplication extends Application
{
public function handleRequest($request)
{
//Si la conexión no es segura, y no está en localhost cambiamos la url para usar SSL
if (!$this->isSecuredByAWS() && !$this->isLocalhost() && !$this->isHealthCheck()) {
//otherwise redirect to same url with https
$secureUrl = str_replace('http', 'https', $request->absoluteUrl);
//use 301 for a permanent redirect
return Yii::$app->getResponse()->redirect($secureUrl, 301);
} else {
//if secure connection call parent implementation
return parent::handleRequest($request);
}
}
/**
* Al estar detrás de un balanceador de carga no sabemos el protocolo,
* sin embargo AWS agrega como header HTTP_X_FORWARDED_PROTO
*/
function isSecuredByAWS()
{
//Si el header está, y es https quiere decir que está asegurado a través de un balanceador de carga
if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == "https") {
return true;
} else {
return false;
}
}
/**
* Retornamos true si estamos en localhost
* @return bool
*/
function isLocalhost()
{
return $_SERVER['SERVER_NAME'] == 'localhost' ;
}
function isHealthCheck()
{
return $_SERVER['REQUEST_URI'] == '/health-check' ;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment