How to improve the speed of a redirect to a subdomain depending on user language?
I'm optimizing our webpage, and we have notice something we want to dramatically improve. We use Symfony 1.3.
When the user loads example.com, the filters (rendering, security and remember) are executed. Then we execute our subdomain filter. If it's the first time the user is here, we get the preferred language of his browser and we redirect the webpage to en.example.com or es.example.com. If the user has a session, we get the language from its session; and we redirect to the subdomain. Then the en.example.com page loads again.
We lose around 1.5 seconds on that redirect. The en.example.com loads sometimes faster than that. How we can get rid o开发者_运维问答f that delay? Changing the index.php and doing the browser-memcache-or-db queries directly without loading symfony?
thanks a lot!
You could use mod_rewrite like this
RewriteCond %{HTTP:Accept-Language} ^es [NC]
RewriteRule ^(.*)$ http://es\.example\.com/$1 [R=301,L]
for every supported language. No PHP involved, no session required, just fast.
I finally made the redirection on index.php. From 1 to 1.5 seconds to 40ms. Something like:
<?php
$host = $_SERVER['HTTP_HOST'];
$host_a = explode('.', $host);
// if subdomain is not in the supported langs
$langs = array('en', 'es');
if( !in_array($host_a[0], $langs) ){
// try to get the cookie and the user culture
$cookie = $_COOKIE['symfony'];
list($id, $signature) = explode(':', $cookie, 2);
if( $signature == sha1($id.':'.'secret_cookie') )
{
// get cookie data from memcache
$memcache_obj = memcache_connect('localhost', 11211);
// the cookie is built with two parts separated by :
// - md5 of the sfCache directory
// - $id from the user
$md5_dir = md5(dirname(dirname(dirname(__FILE__)).'/lib/vendor/symfony/lib/cache/sfCache.class.php'));
$session = memcache_get($memcache_obj, $md5_dir.':'.$id);
$user_lang = $session['symfony/user/sfUser/culture'];
if( !in_array($user_lang, $langs) ) $user_lang = 'en';
// if not, get browser lang
}else{
$user_lang = prefered_language($langs);
}
// build url
$url = 'http://'.$user_lang.'.'.str_replace('www.', '', $_SERVER['HTTP_HOST']).$_SERVER['REQUEST_URI'];
// and redirect
Header( "HTTP/1.1 301 Moved Permanently" );
Header( "Location: ".$url);
die();
}
require_once(dirname(__FILE__).'/../config/ProjectConfiguration.class.php');
$configuration = ProjectConfiguration::getApplicationConfiguration('frontend', 'prod', false);
sfContext::createInstance($configuration)->dispatch();
精彩评论