UrlLanguageManager
API reference › Locale URLs › UrlLanguageManager
Resolves the application language from a URL code, the persisted choice, the browser, or GeoIP, and adds the language code to created URLs.
A URL without a code redirects to the persisted or detected language; a URL with the default language code redirects
to the URL without it unless $enableDefaultLanguageUrlCode is true.
The manager keeps no per-request state and is safe for long-running workers; redirects are raised as
UrlNormalizerRedirectException and handled by the application.
See also: LanguageChangedEvent.
Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$baseUrl | string | The base URL that is used by createUrl() to prepend to created URLs. | yii\ |
$behaviors read-only | array<yii\<static>> | List of behaviors attached to this component. | yii\ |
$cache | yii\| | The cache object or the application component ID of the cache object. Default: 'cache'. | yii\ |
$defaultLanguage | string| | Default language: the language of URLs without a code when $enableDefaultLanguageUrlCode is false. Default: null. | UrlLanguageManager |
$enableDefaultLanguageUrlCode | bool | Whether the default language uses a URL code like any other language. Default: false. | UrlLanguageManager |
$enableLanguageDetection | bool | Whether to detect the language from the Accept-Language header when the URL has no code and no language is persisted. Default: true. | UrlLanguageManager |
$enableLanguagePersistence | bool | Whether to persist the language from the URL in the session and the language cookie. Default: true. | UrlLanguageManager |
$enableLocaleUrls | bool | Whether to enable language processing; when false, the manager behaves like UrlManager. Default: true. | UrlLanguageManager |
$enablePrettyUrl | Whether to enable pretty URLs; must be true while locale URLs are enabled. Default: true. | UrlLanguageManager | |
$enableStrictParsing | bool | Whether to enable strict parsing. Default: false. | yii\ |
$geoIpLanguageCountries | array | GeoIP country codes indexed by the language they select. Default: []. | UrlLanguageManager |
$geoIpServerVar | string | Name of the server variable that carries the GeoIP country code. Default: 'HTTP_X_GEO_COUNTRY'. | UrlLanguageManager |
$hostInfo | string | The host info (e.g. https://www.example.com) that is used by createAbsoluteUrl() to prepend to created URLs. | yii\ |
$ignoreLanguageUrlPatterns | array | Regular expressions that exclude routes and URLs from language processing. Default: []. | UrlLanguageManager |
$keepUppercaseLanguageCode | bool | Whether to keep uppercase letters of language codes in URLs. Default: false. | UrlLanguageManager |
$languageCookieDuration | int | Lifetime of the language cookie in seconds; 0 disables the cookie. Default: 2592000. | UrlLanguageManager |
$languageCookieName | string | Name of the language cookie. Default: '_language'. | UrlLanguageManager |
$languageCookieOptions | array | Additional Cookie properties for the language cookie. Default: []. | UrlLanguageManager |
$languageParam | string | Name of the createUrl() parameter that selects the language of the created URL. Default: 'language'. | UrlLanguageManager |
$languageRedirectCode | int | HTTP status code of language redirects. Default: 302. | UrlLanguageManager |
$languages | array | Available languages: codes (en-US), wildcards (es-*), or URL aliases mapped to codes ('english' => 'en'). Default: []. | UrlLanguageManager |
$languageSessionKey | string| | Session key that stores the language; false disables session persistence. Default: '_language'. | UrlLanguageManager |
$normalizer | yii\| | The configuration for UrlNormalizer used by this UrlManager. Default: false. Available since 2.0.10. | yii\ |
$routeParam | string | The GET parameter name for route. Default: 'r'. | yii\ |
$ruleConfig | array | The default configuration of URL rules. Default: ['class' => 'yii\. | yii\ |
$rules | array | The rules for creating and parsing URLs when $enablePrettyUrl is true. Default: []. | yii\ |
$scriptUrl | string | The entry script URL that is used by createUrl() to prepend to created URLs. | yii\ |
$showScriptName | bool | Whether to show entry script name in the constructed URL. Default: true. | yii\ |
$suffix | string | The URL suffix used when $enablePrettyUrl is true. Default: null. | yii\ |
$_defaultLanguage protected | string | Default language resolved by init() from $defaultLanguage or the application language. Default: ''. | UrlLanguageManager |
$cacheKey protected | string | The cache key for cached rules Default: __CLASS__. Available since 2.0.8. | yii\ |
Methods
Section titled “Methods”| Method | Description | Defined by |
|---|---|---|
__construct() | Constructor. | yii\ |
__call() | Calls the named method which is not a class method. | yii\ |
__clone() | This method is called after the object is created by cloning an existing one. | yii\ |
__get() | Returns the value of a component property. | yii\ |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\ |
__set() | Sets the value of a component property. | yii\ |
__unset() | Sets a component property to be null. | yii\ |
addRules() | Adds additional URL rules. | yii\ |
attachBehavior() | Attaches a behavior to this component. | yii\ |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\ |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\ |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\ |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\ |
className() static | Returns the fully qualified name of this class. | yii\ |
createAbsoluteUrl() | Creates an absolute URL using the given route and query parameters. | yii\ |
createUrl() | Creates a URL and inserts the language code after the base URL or the script name. | UrlLanguageManager |
detachBehavior() | Detaches a behavior from the component. | yii\ |
detachBehaviors() | Detaches all behaviors from the component. | yii\ |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\ |
getBaseUrl() | Returns the base URL that is used by createUrl() to prepend to created URLs. | yii\ |
getBehavior() | Returns the named behavior object. | yii\ |
getBehaviors() | Returns all behaviors attached to this component. | yii\ |
getDefaultLanguage() | Returns the default language: $defaultLanguage, or the application language captured when the manager was initialized. | UrlLanguageManager |
getHostInfo() | Returns the host info that is used by createAbsoluteUrl() to prepend to created URLs. | yii\ |
getScriptUrl() | Returns the entry script URL that is used by createUrl() to prepend to created URLs. | yii\ |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. | yii\ |
hasMethod() | Returns a value indicating whether a method is defined. | yii\ |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\ |
init() | Captures the default language and validates the configuration. | UrlLanguageManager |
off() | Detaches an existing event handler from this component. | yii\ |
on() | Attaches an event handler to an event. | yii\ |
parseRequest() | Resolves the request language, removes its code from the path info, and parses the request. | UrlLanguageManager |
setBaseUrl() | Sets the base URL that is used by createUrl() to prepend to created URLs. | yii\ |
setHostInfo() | Sets the host info that is used by createAbsoluteUrl() to prepend to created URLs. | yii\ |
setScriptUrl() | Sets the entry script URL that is used by createUrl() to prepend to created URLs. | yii\ |
trigger() | Triggers an event. | yii\ |
buildRules() protected | Builds URL rule objects from the given rule declarations. | yii\ |
canBeCached() protected | Returns the value indicating whether result of createUrl() of rule should be cached in internal cache. | yii\ |
detectLanguage() protected | Detects the language from the Accept-Language header, then from the GeoIP country. | UrlLanguageManager |
getBuiltRulesFromCache() protected | Provides the built URL rules that are associated with the $ruleDeclarations from cache. | yii\ |
getUrlFromCache() protected | Get URL from internal cache if exists. | yii\ |
loadPersistedLanguage() protected | Returns the language persisted in the session or, failing that, in the language cookie. | UrlLanguageManager |
matchCode() protected | Matches a language code against $languages, case-insensitively and including wildcards. | UrlLanguageManager |
persistLanguage() protected | Stores the language in the session and the language cookie. | UrlLanguageManager |
processLocaleUrl() protected | Resolves the language of the request and returns the language redirect it requires. | UrlLanguageManager |
setBuiltRulesCache() protected | Stores $builtRules to cache, using $rulesDeclaration as a part of cache key. | yii\ |
setRuleToCache() protected | Store rule (e.g. UrlRule) to internal cache. | yii\ |
Events
Section titled “Events”| Event | Type | Description | Defined by |
|---|---|---|---|
EVENT_LANGUAGE_CHANGED | LanguageChangedEvent | Raised before a language from the URL that differs from the persisted one is persisted. Event name: 'languageChanged'. | UrlLanguageManager |
Property details
Section titled “Property details”$defaultLanguage
Section titled “$defaultLanguage ”public string|null $defaultLanguage = nullDefault language: the language of URLs without a code when $enableDefaultLanguageUrlCode is false.
null captures Yii::$app->language in init(). Set it explicitly in long-running workers, where the
application object and its language persist between requests; it is also applied to Yii::$app->language at the
start of each request.
$enableDefaultLanguageUrlCode
Section titled “$enableDefaultLanguageUrlCode ”public bool $enableDefaultLanguageUrlCode = falseWhether the default language uses a URL code like any other language.
When false, a URL without a code uses the default language, and a URL with the default code redirects to the
URL without it (default fr: /fr/some/page -> /some/page), which also resets the persisted language. When
true, a URL without a code redirects to the default code (/some/page -> /fr/some/page).
$enableLanguageDetection
Section titled “$enableLanguageDetection ”public bool $enableLanguageDetection = trueWhether to detect the language from the Accept-Language header when the URL has no code and no language is
persisted.
GeoIP detection through $geoIpLanguageCountries applies regardless of this setting.
$enableLanguagePersistence
Section titled “$enableLanguagePersistence ”public bool $enableLanguagePersistence = trueWhether to persist the language from the URL in the session and the language cookie.
When true, a URL without a code redirects to the persisted language (/some/page -> /fr/some/page).
$enablePrettyUrl
Section titled “$enablePrettyUrl ”public $enablePrettyUrl = trueWhether to enable pretty URLs; must be true while locale URLs are enabled.
Declared without a native type to match UrlManager::$enablePrettyUrl.
$geoIpLanguageCountries
Section titled “$geoIpLanguageCountries ”public array $geoIpLanguageCountries = []GeoIP country codes indexed by the language they select.
[ 'de' => ['DEU', 'AUT'], 'ru' => ['RUS', 'BLR', 'KAZ'],]$geoIpServerVar
Section titled “$geoIpServerVar ”public string $geoIpServerVar = 'HTTP_X_GEO_COUNTRY'Name of the server variable that carries the GeoIP country code.
Names starting with HTTP_ are read as the request header they represent (HTTP_X_GEO_COUNTRY ->
X-Geo-Country); other names are read from getServerParams() when the request provides it, otherwise from
$_SERVER.
$ignoreLanguageUrlPatterns
Section titled “$ignoreLanguageUrlPatterns ”public array $ignoreLanguageUrlPatterns = []Regular expressions that exclude routes and URLs from language processing.
Keys match routes in createUrl(), which then adds no language code; values match the path info in
parseRequest(), which then resolves no language.
The first pair assumes URL rules that map login and register to site/login and site/register.
[ '#^site/(login|register)#' => '#^(login|register)#', '#^api/#' => '#^api/#',]$keepUppercaseLanguageCode
Section titled “$keepUppercaseLanguageCode ”public bool $keepUppercaseLanguageCode = falseWhether to keep uppercase letters of language codes in URLs.
When false, created URLs use lowercase codes, and a URL with an uppercase country (/de-AT/page) or with an
alias spelled differently from its configuration (/AT/page) redirects to the lowercase URL.
$languageCookieDuration
Section titled “$languageCookieDuration ”public int $languageCookieDuration = 2592000Lifetime of the language cookie in seconds; 0 disables the cookie.
Applies only when $enableLanguagePersistence is true.
$languageCookieOptions
Section titled “$languageCookieOptions ”public array $languageCookieOptions = []Additional Cookie properties for the language cookie.
httpOnly defaults to true; name, value, and expire always come from $languageCookieName, the
language, and $languageCookieDuration.
$languageParam
Section titled “$languageParam ”public string $languageParam = 'language'Name of the createUrl() parameter that selects the language of the created URL.
URLs created with this parameter switch to that language; without it, the current application language is used.
$languageRedirectCode
Section titled “$languageRedirectCode ”public int $languageRedirectCode = 302HTTP status code of language redirects.
Redirects caused only by the URL normalizer keep the normalizer status code.
Method details
Section titled “Method details”createUrl()
Section titled “createUrl() ”public function createUrl(array|string $params): stringCreates a URL and inserts the language code after the base URL or the script name.
Parameters
| Parameter | Type | Description |
|---|---|---|
$params | array| | Route and parameters; $languageParam selects the language of the URL. |
Returns
string: Created URL.
Throws
yii\base\InvalidConfigException: if the base URL or the script URL cannot be determined.
getDefaultLanguage()
Section titled “getDefaultLanguage() ”public function getDefaultLanguage(): stringReturns the default language: $defaultLanguage, or the application language captured when the manager was
initialized.
Returns
string: Default language code, for example en.
init()
Section titled “init() ”public function init(): voidCaptures the default language and validates the configuration.
Throws
yii\base\InvalidConfigException: if locale URLs are enabled while$enablePrettyUrlisfalse, or if the parent configuration is invalid.
parseRequest()
Section titled “parseRequest() ”public function parseRequest(yii\web\Request $request): array|boolResolves the request language, removes its code from the path info, and parses the request.
Each request object is processed once; later calls only parse it. A request not processed yet first resets
Yii::$app->language to $defaultLanguage when it is set. When the request must move to its canonical
language URL, UrlNormalizerRedirectException carries the target URL and $languageRedirectCode, or
the normalizer status code when only the URL normalizer requires the redirect. A redirect raised by a URL rule
with a string URL is rethrown unchanged.
Parameters
| Parameter | Type | Description |
|---|---|---|
$request | yii\ | Request to parse. |
Returns
array|bool: Route and parameters, or false if no rule matches the request.
Throws
yii\base\InvalidConfigException: if the path info of the request cannot be determined.yii\web\NotFoundHttpException: if no rule matches the request while a language redirect is pending, or if the URL normalizer action isACTION_NOT_FOUNDand the path info is not normalized.yii\web\UrlNormalizerRedirectException: if the request must be redirected.
detectLanguage()
Section titled “detectLanguage() ”protected function detectLanguage(yii\web\Request $request): string|nullDetects the language from the Accept-Language header, then from the GeoIP country.
Parameters
| Parameter | Type | Description |
|---|---|---|
$request | yii\ | Request that provides the header and the GeoIP country. |
Returns
string|null: Detected language code, or null if no configured language matches.
loadPersistedLanguage()
Section titled “loadPersistedLanguage() ”protected function loadPersistedLanguage(yii\web\Request $request): string|nullReturns the language persisted in the session or, failing that, in the language cookie.
Parameters
| Parameter | Type | Description |
|---|---|---|
$request | yii\ | Request that provides the language cookie. |
Returns
string|null: Persisted language code, or null if none is stored.
matchCode()
Section titled “matchCode() ”protected function matchCode(string $code): arrayMatches a language code against $languages, case-insensitively and including wildcards.
Exact matches skip wildcards and return the configured spelling. A wildcard match (es-*) returns the configured
spelling of the language and the first subtag when it is a 2-3 letter region, in uppercase: ES-mx-variant ->
['es', 'MX']; any other subtag is dropped: es-Latn -> ['es', null]. A code whose region is not configured
falls back to its language when that language is configured: de-CH -> ['de', null].
Parameters
| Parameter | Type | Description |
|---|---|---|
$code | string | Language code to match, for example en, en-US, or es-MX. |
Returns
array: Matched language and country, or [null, null] if no configured language matches.
persistLanguage()
Section titled “persistLanguage() ”protected function persistLanguage(yii\web\Request $request, string $language): voidStores the language in the session and the language cookie.
Triggers EVENT_LANGUAGE_CHANGED first when handlers are attached and the language differs from the
persisted one.
Parameters
| Parameter | Type | Description |
|---|---|---|
$request | yii\ | Request that provides the previously persisted language. |
$language | string | Language code to persist, for example en or de-AT. |
processLocaleUrl()
Section titled “processLocaleUrl() ”protected function processLocaleUrl(yii\web\Request $request): string|nullResolves the language of the request and returns the language redirect it requires.
A language code at the start of the path info is removed from it, applied to Yii::$app->language, and
persisted. Without a code, the persisted language, then the detected language, then (with
$enableDefaultLanguageUrlCode) the default language selects the redirect target.
Parameters
| Parameter | Type | Description |
|---|---|---|
$request | yii\ | Request whose path info is processed. |
Returns
string|null: Language code or alias to redirect to, '' to redirect to the URL without a language code, or null if no language redirect is required.
Throws
yii\base\InvalidConfigException: if the path info of the request cannot be determined.