Boucle de redirection prestashop 1.6

Voici comment contourner le problème des boucles de redirections que l’on peut parfois rencontrer avec prestashop 1.6

J’ai expliqué dans cet article comment afficher un site installé en local via un ipad ou iphone (ou tout autre mobile). Le problème c’est que souvent cela génère une boucle de redirection. Voici deux overrides qui vont vous permettre de contourner le problème.

override\classes\shop\Shop.php


class Shop extends ShopCore
{
public static function initialize()
{
// Find current shop from URL
if (!($id_shop = Tools::getValue('id_shop')) || defined('_PS_ADMIN_DIR_'))
{
$found_uri = '';
$is_main_uri = false;
$host = Tools::getHttpHost();
$request_uri = rawurldecode($_SERVER['REQUEST_URI']);
$request_uri=str_replace('http://'.$_SERVER['HTTP_HOST'],'',$request_uri);

$sql = 'SELECT s.id_shop, CONCAT(su.physical_uri, su.virtual_uri) AS uri, su.domain, su.main
FROM '._DB_PREFIX_.'shop_url su
LEFT JOIN '._DB_PREFIX_.'shop s ON (s.id_shop = su.id_shop)
WHERE (su.domain = \''. pSQL($host).'\' OR su.domain_ssl = \''. pSQL($host).'\')
AND s.active = 1
AND s.deleted = 0
ORDER BY LENGTH(CONCAT(su.physical_uri, su.virtual_uri)) DESC';

$result = Db::getInstance()->executeS($sql);

$through = false;
foreach ($result as $row)
{
// An URL matching current shop was found
if (preg_match('#^'.preg_quote($row['uri'], '#').'#i', $request_uri))
{
$through = true;
$id_shop = $row['id_shop'];
$found_uri = $row['uri'];
if ($row['main'])
$is_main_uri = true;
break;
}
}

// If an URL was found but is not the main URL, redirect to main URL
if ($through && $id_shop && !$is_main_uri)
{

foreach ($result as $row)
{
if ($row['id_shop'] == $id_shop && $row['main'])
{
$request_uri = substr($request_uri, strlen($found_uri));
$url = str_replace('//', '/', $row['domain'].$row['uri'].$request_uri);
$redirect_type = Configuration::get('PS_CANONICAL_REDIRECT') == 2 ? '301' : '302';
header('HTTP/1.0 '.$redirect_type.' Moved');
header('Cache-Control: no-cache');
header('location: http://'.$url);
exit;
}
}
}
}

if ((!$id_shop && defined('_PS_ADMIN_DIR_')) || Tools::isPHPCLI() || in_array(Tools::getHttpHost(), array(_MEDIA_SERVER_1_, _MEDIA_SERVER_2_, _MEDIA_SERVER_3_)))
{
// If in admin, we can access to the shop without right URL
if ((!$id_shop && Tools::isPHPCLI()) || defined('_PS_ADMIN_DIR_'))
$id_shop = (int)Configuration::get('PS_SHOP_DEFAULT');

$shop = new Shop((int)$id_shop);
if (!Validate::isLoadedObject($shop))
$shop = new Shop((int)Configuration::get('PS_SHOP_DEFAULT'));

$shop->physical_uri = preg_replace('#/+#', '/', str_replace('\\', '/', dirname(dirname($_SERVER['SCRIPT_NAME']))).'/');
$shop->virtual_uri = '';

// Define some $_SERVER variables like HTTP_HOST if PHP is launched with php-cli
if (Tools::isPHPCLI())
{
if (!isset($_SERVER['HTTP_HOST']) || empty($_SERVER['HTTP_HOST']))
$_SERVER['HTTP_HOST'] = $shop->domain;
if (!isset($_SERVER['SERVER_NAME']) || empty($_SERVER['SERVER_NAME']))
$_SERVER['SERVER_NAME'] = $shop->domain;
if (!isset($_SERVER['REMOTE_ADDR']) || empty($_SERVER['REMOTE_ADDR']))
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
}
}
else
{
$shop = new Shop($id_shop);
if (!Validate::isLoadedObject($shop) || !$shop->active)
{
// No shop found ... too bad, let's redirect to default shop
$default_shop = new Shop(Configuration::get('PS_SHOP_DEFAULT'));

// Hmm there is something really bad in your Prestashop !
if (!Validate::isLoadedObject($default_shop))
throw new PrestaShopException('Shop not found');

$params = $_GET;
unset($params['id_shop']);
$url = $default_shop->domain;
if (!Configuration::get('PS_REWRITING_SETTINGS'))
$url .= $default_shop->getBaseURI().'index.php?'.http_build_query($params);
else
{
// Catch url with subdomain "www"
if (strpos($url, 'www.') === 0 && 'www.'.$_SERVER['HTTP_HOST'] === $url || $_SERVER['HTTP_HOST'] === 'www.'.$url)
$url .= $_SERVER['REQUEST_URI'];
else
$url .= $default_shop->getBaseURI();

if (count($params))
$url .= '?'.http_build_query($params);
}
$redirect_type = Configuration::get('PS_CANONICAL_REDIRECT') == 2 ? '301' : '302';
header('HTTP/1.0 '.$redirect_type.' Moved');
header('location: http://'.$url);
exit;
}
elseif (defined('_PS_ADMIN_DIR_') && empty($shop->physical_uri))
{
$shop_default = new Shop((int)Configuration::get('PS_SHOP_DEFAULT'));
$shop->physical_uri = $shop_default->physical_uri;
$shop->virtual_uri = $shop_default->virtual_uri;
}
}

self::$context_id_shop = $shop->id;
self::$context_id_shop_group = $shop->id_shop_group;
self::$context = self::CONTEXT_SHOP;

return $shop;
}
}

override\classes\controller\FrontController.php


class FrontController extends FrontControllerCore
{
protected function canonicalRedirection($canonical_url = '')
{
if (!$canonical_url || !Configuration::get('PS_CANONICAL_REDIRECT') || strtoupper($_SERVER['REQUEST_METHOD']) != 'GET' || Tools::getValue('live_edit'))
return;

$request_uri=str_replace('http://'.$_SERVER['HTTP_HOST'],'',$_SERVER['REQUEST_URI']);
$match_url = rawurldecode(Tools::getCurrentUrlProtocolPrefix().$_SERVER['HTTP_HOST'].$request_uri);
if (!preg_match('/^'.Tools::pRegexp(rawurldecode($canonical_url), '/').'([&?].*)?$/', $match_url))
{
$params = array();
$str_params = '';
$url_details = parse_url($canonical_url);

if (!empty($url_details['query']))
{
parse_str($url_details['query'], $query);
foreach ($query as $key => $value)
$params[Tools::safeOutput($key)] = Tools::safeOutput($value);
}
$excluded_key = array('isolang', 'id_lang', 'controller', 'fc', 'id_product', 'id_category', 'id_manufacturer', 'id_supplier', 'id_cms');
foreach ($_GET as $key => $value)
if (!in_array($key, $excluded_key) && Validate::isUrl($key) && Validate::isUrl($value))
$params[Tools::safeOutput($key)] = Tools::safeOutput($value);

$str_params = http_build_query($params, '', '&');
if (!empty($str_params))
$final_url = preg_replace('/^([^?]*)?.*$/', '$1', $canonical_url).'?'.$str_params;
else
$final_url = preg_replace('/^([^?]*)?.*$/', '$1', $canonical_url);

// Don't send any cookie
Context::getContext()->cookie->disallowWriting();

if (defined('_PS_MODE_DEV_') && _PS_MODE_DEV_ && $_SERVER['REQUEST_URI'] != __PS_BASE_URI__)
die('[Debug] This page has moved<br />Please use the following URL instead: <a href="'.$final_url.'">'.$final_url.'</a>');

$redirect_type = Configuration::get('PS_CANONICAL_REDIRECT') == 2 ? '301' : '302';
header('HTTP/1.0 '.$redirect_type.' Moved');
header('Cache-Control: no-cache');
Tools::redirectLink($final_url);
}
}
}

Si vous avez un problème de page introuvable essayez de désactiver la réécriture d’url et la redirection vers l’url canonique.

Enfin voici le même correctif pour prestashop 1.5

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *