Skip to content
PHP Ecosystem
Explore

UrlManager

API reference › yii › web › UrlManager

classyii\web\UrlManager
Extendsyii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable
Since2.0
Sourceframework/web/UrlManager.php
1 subclass

UrlManager handles HTTP request parsing and creation of URLs based on a set of rules.

UrlManager is configured as an application component in Application by default. You can access that instance via Yii::$app->urlManager.

You can modify its configuration by adding an array to your application config under components as it is shown in the following example:

'urlManager' => [
'enablePrettyUrl' => true,
'rules' => [
// your rules go here
],
// ...
]

Rules are classes implementing the UrlRuleInterface, by default that is UrlRule. For nesting rules, there is also a GroupUrlRule class.

For more details and usage information on UrlManager, see the guide article on routing.

PropertyTypeDescriptionDefined by
$baseUrlstringThe base URL that is used by createUrl() to prepend to created URLs.UrlManager
$behaviors read-onlyarray<yii\base\Behavior<static>>List of behaviors attached to this component.yii\base\Component
$cacheyii\caching\CacheInterface|array|string|bool|nullThe cache object or the application component ID of the cache object. Default: 'cache'.UrlManager
$enablePrettyUrlboolWhether to enable pretty URLs. Default: false.UrlManager
$enableStrictParsingboolWhether to enable strict parsing. Default: false.UrlManager
$hostInfostringThe host info (e.g. https://www.example.com) that is used by createAbsoluteUrl() to prepend to created URLs.UrlManager
$normalizerUrlNormalizer|array|string|falseThe configuration for UrlNormalizer used by this UrlManager. Default: false. Available since 2.0.10.UrlManager
$routeParamstringThe GET parameter name for route. Default: 'r'.UrlManager
$ruleConfigarrayThe default configuration of URL rules. Default: ['class' => 'yii\web\UrlRule'].UrlManager
$rulesarrayThe rules for creating and parsing URLs when $enablePrettyUrl is true. Default: [].UrlManager
$scriptUrlstringThe entry script URL that is used by createUrl() to prepend to created URLs.UrlManager
$showScriptNameboolWhether to show entry script name in the constructed URL. Default: true.UrlManager
$suffixstringThe URL suffix used when $enablePrettyUrl is true. Default: null.UrlManager
$cacheKey protectedstringThe cache key for cached rules Default: __CLASS__. Available since 2.0.8.UrlManager
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__call()Calls the named method which is not a class method.yii\base\Component
__clone()This method is called after the object is created by cloning an existing one.yii\base\Component
__get()Returns the value of a component property.yii\base\Component
__isset()Checks if a property is set, i.e. defined and not null.yii\base\Component
__set()Sets the value of a component property.yii\base\Component
__unset()Sets a component property to be null.yii\base\Component
addRules()Adds additional URL rules.UrlManager
attachBehavior()Attaches a behavior to this component.yii\base\Component
attachBehaviors()Attaches a list of behaviors to the component.yii\base\Component
behaviors()Returns a list of behaviors that this component should behave as.yii\base\Component
canGetProperty()Returns a value indicating whether a property can be read.yii\base\Component
canSetProperty()Returns a value indicating whether a property can be set.yii\base\Component
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
createAbsoluteUrl()Creates an absolute URL using the given route and query parameters.UrlManager
createUrl()Creates a URL using the given route and query parameters.UrlManager
detachBehavior()Detaches a behavior from the component.yii\base\Component
detachBehaviors()Detaches all behaviors from the component.yii\base\Component
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.yii\base\Component
getBaseUrl()Returns the base URL that is used by createUrl() to prepend to created URLs.UrlManager
getBehavior()Returns the named behavior object.yii\base\Component
getBehaviors()Returns all behaviors attached to this component.yii\base\Component
getHostInfo()Returns the host info that is used by createAbsoluteUrl() to prepend to created URLs.UrlManager
getScriptUrl()Returns the entry script URL that is used by createUrl() to prepend to created URLs.UrlManager
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.yii\base\Component
hasMethod()Returns a value indicating whether a method is defined.yii\base\Component
hasProperty()Returns a value indicating whether a property is defined for this component.yii\base\Component
init()Initializes UrlManager.UrlManager
off()Detaches an existing event handler from this component.yii\base\Component
on()Attaches an event handler to an event.yii\base\Component
parseRequest()Parses the user request.UrlManager
setBaseUrl()Sets the base URL that is used by createUrl() to prepend to created URLs.UrlManager
setHostInfo()Sets the host info that is used by createAbsoluteUrl() to prepend to created URLs.UrlManager
setScriptUrl()Sets the entry script URL that is used by createUrl() to prepend to created URLs.UrlManager
trigger()Triggers an event.yii\base\Component
buildRules() protectedBuilds URL rule objects from the given rule declarations.UrlManager
canBeCached() protectedReturns the value indicating whether result of createUrl() of rule should be cached in internal cache.UrlManager
getBuiltRulesFromCache() protectedProvides the built URL rules that are associated with the $ruleDeclarations from cache.UrlManager
getUrlFromCache() protectedGet URL from internal cache if exists.UrlManager
setBuiltRulesCache() protectedStores $builtRules to cache, using $rulesDeclaration as a part of cache key.UrlManager
setRuleToCache() protectedStore rule (e.g. UrlRule) to internal cache.UrlManager
public yii\caching\CacheInterface|array|string|bool|null $cache = 'cache'

The cache object or the application component ID of the cache object.

This can also be an array that is used to create a CacheInterface instance in case you do not want to use an application component. Compiled URL rules will be cached through this cache object, if it is available.

After the UrlManager object is created, if you want to change this property, you should only assign it with a cache object. Set this property to false or null if you do not want to cache the URL rules.

Cache entries are stored for the time set by $defaultDuration in the cache configuration, which is unlimited by default. You may want to tune this value if your $rules change frequently.

public bool $enablePrettyUrl = false

Whether to enable pretty URLs.

Instead of putting all parameters in the query string part of a URL, pretty URLs allow using path info to represent some of the parameters and can thus produce more user-friendly URLs, such as “/news/Yii-is-released”, instead of “/index.php?r=news%2Fview&id=100”.

public bool $enableStrictParsing = false

Whether to enable strict parsing.

If strict parsing is enabled, the incoming requested URL must match at least one of the $rules in order to be treated as a valid request. Otherwise, the path info part of the request will be treated as the requested route. This property is used only when $enablePrettyUrl is true.

public yii\web\UrlNormalizer|array|string|false $normalizer = false

The configuration for UrlNormalizer used by this UrlManager.

The default value is false, which means normalization will be skipped. If you wish to enable URL normalization, you should configure this property manually. For example:

[
'class' => 'yii\web\UrlNormalizer',
'collapseSlashes' => true,
'normalizeTrailingSlash' => true,
]

Since

2.0.10

public string $routeParam = 'r'

The GET parameter name for route.

This property is used only if $enablePrettyUrl is false.

public array $ruleConfig = ['class' => 'yii\web\UrlRule']

The default configuration of URL rules.

Individual rule configurations specified via $rules will take precedence when the same property of the rule is configured.

public array $rules = []

The rules for creating and parsing URLs when $enablePrettyUrl is true.

This property is used only if $enablePrettyUrl is true. Each element in the array is the configuration array for creating a single URL rule. The configuration will be merged with $ruleConfig first before it is used for creating the rule object.

A special shortcut format can be used if a rule only specifies pattern and route: 'pattern' => 'route'. That is, instead of using a configuration array, one can use the key to represent the pattern and the value the corresponding route. For example, 'post/<id:\d+>' => 'post/view'.

For RESTful routing the mentioned shortcut format also allows you to specify the HTTP verb that the rule should apply for. You can do that by prepending it to the pattern, separated by space. For example, 'PUT post/<id:\d+>' => 'post/update'. You may specify multiple verbs by separating them with comma like this: 'POST,PUT post/index' => 'post/create'. The supported verbs in the shortcut format are: GET, HEAD, POST, PUT, PATCH and DELETE. Note that mode will be set to PARSING_ONLY when specifying verb in this way so you normally would not specify a verb for normal GET request.

Here is an example configuration for RESTful CRUD controller:

[
'dashboard' => 'site/index',
'POST <controller:[\w-]+>' => '<controller>/create',
'<controller:[\w-]+>s' => '<controller>/index',
'PUT <controller:[\w-]+>/<id:\d+>' => '<controller>/update',
'DELETE <controller:[\w-]+>/<id:\d+>' => '<controller>/delete',
'<controller:[\w-]+>/<id:\d+>' => '<controller>/view',
];

Note that if you modify this property after the UrlManager object is created, make sure you populate the array with rule objects instead of rule configurations.

public bool $showScriptName = true

Whether to show entry script name in the constructed URL.

Defaults to true. This property is used only if $enablePrettyUrl is true.

public string $suffix = null

The URL suffix used when $enablePrettyUrl is true.

For example, “.html” can be used so that the URL looks like pointing to a static HTML page. This property is used only if $enablePrettyUrl is true.

public function addRules(array $rules, bool $append = true): mixed

Adds additional URL rules.

This method will call buildRules() to parse the given rule declarations and then append or insert them to the existing $rules.

Note that if $enablePrettyUrl is false, this method will do nothing.

Parameters

ParameterTypeDescription
$rulesarrayThe new rules to be added. Each array element represents a single rule declaration. Please refer to $rules for the acceptable rule format.
$appendboolWhether to add the new rules by appending them to the end of the existing rules.

Returns

mixed

public function createAbsoluteUrl(string|array $params, string|null $scheme = null): string

Creates an absolute URL using the given route and query parameters.

This method prepends the URL created by createUrl() with the $hostInfo.

Note that unlike Url::toRoute(), this method always treats the given route as an absolute route.

Parameters

ParameterTypeDescription
$paramsstring|arrayUse a string to represent a route (e.g. site/index), or an array to represent a route with query parameters (e.g. ['site/index', 'param1' => 'value1']).
$schemestring|nullThe scheme to use for the URL (either http, https or empty string for protocol-relative URL). If not specified the scheme of the current request will be used.

Returns

string: The created URL

See also

public function createUrl(string|array $params): string

Creates a URL using the given route and query parameters.

You may specify the route as a string, e.g., site/index. You may also use an array if you want to specify additional query parameters for the URL being created. The array format must be:

// generates: /index.php?r=site%2Findex&param1=value1&param2=value2
['site/index', 'param1' => 'value1', 'param2' => 'value2']

If you want to create a URL with an anchor, you can use the array format with a # parameter. For example,

// generates: /index.php?r=site%2Findex&param1=value1#name
['site/index', 'param1' => 'value1', '#' => 'name']

The URL created is a relative one. Use createAbsoluteUrl() to create an absolute URL.

Note that unlike Url::toRoute(), this method always treats the given route as an absolute route.

Parameters

ParameterTypeDescription
$paramsstring|arrayUse a string to represent a route (e.g. site/index), or an array to represent a route with query parameters (e.g. ['site/index', 'param1' => 'value1']).

Returns

string: The created URL

public function getBaseUrl(): string

Returns the base URL that is used by createUrl() to prepend to created URLs.

It defaults to Request::$baseUrl. This is mainly used when $enablePrettyUrl is true and $showScriptName is false.

Returns

string: The base URL that is used by createUrl() to prepend to created URLs.

Throws

public function getHostInfo(): string

Returns the host info that is used by createAbsoluteUrl() to prepend to created URLs.

Returns

string: The host info (e.g. https://www.example.com) that is used by createAbsoluteUrl() to prepend to created URLs.

Throws

public function getScriptUrl(): string

Returns the entry script URL that is used by createUrl() to prepend to created URLs.

It defaults to Request::$scriptUrl. This is mainly used when $enablePrettyUrl is false or $showScriptName is true.

Returns

string: The entry script URL that is used by createUrl() to prepend to created URLs.

Throws

public function init(): mixed

Initializes UrlManager.

Returns

mixed

public function parseRequest(yii\web\Request $request): array|bool

Parses the user request.

Parameters

ParameterTypeDescription
$requestRequestThe request component

Returns

array|bool: The route and the associated parameters. The latter is always empty if $enablePrettyUrl is false. false is returned if the current request cannot be successfully parsed.

public function setBaseUrl(string $value): mixed

Sets the base URL that is used by createUrl() to prepend to created URLs.

This is mainly used when $enablePrettyUrl is true and $showScriptName is false.

Parameters

ParameterTypeDescription
$valuestringThe base URL that is used by createUrl() to prepend to created URLs.

Returns

mixed

public function setHostInfo(string $value): mixed

Sets the host info that is used by createAbsoluteUrl() to prepend to created URLs.

Parameters

ParameterTypeDescription
$valuestringThe host info (e.g. “https://www.example.com”) that is used by createAbsoluteUrl() to prepend to created URLs.

Returns

mixed

public function setScriptUrl(string $value): mixed

Sets the entry script URL that is used by createUrl() to prepend to created URLs.

This is mainly used when $enablePrettyUrl is false or $showScriptName is true.

Parameters

ParameterTypeDescription
$valuestringThe entry script URL that is used by createUrl() to prepend to created URLs.

Returns

mixed

protected function buildRules(array $ruleDeclarations): yii\web\UrlRuleInterface[]

Builds URL rule objects from the given rule declarations.

Parameters

ParameterTypeDescription
$ruleDeclarationsarrayThe rule declarations. Each array element represents a single rule declaration. Please refer to $rules for the acceptable rule formats.

Returns

UrlRuleInterface[]: The rule objects built from the given rule declarations

Throws

protected function canBeCached(yii\web\UrlRuleInterface $rule): bool

Returns the value indicating whether result of createUrl() of rule should be cached in internal cache.

Parameters

ParameterTypeDescription
$ruleUrlRuleInterface

Returns

bool: true if result should be cached, false if not.

Since

2.0.12

See also

protected function getBuiltRulesFromCache(array $ruleDeclarations): yii\web\UrlRuleInterface[]|false

Provides the built URL rules that are associated with the $ruleDeclarations from cache.

Parameters

ParameterTypeDescription
$ruleDeclarationsarrayThe rule declarations. Each array element represents a single rule declaration. Please refer to $rules for the acceptable rule formats.

Returns

UrlRuleInterface[]|false: The rule objects built from the given rule declarations or boolean false when there are no cache items for this definition exists.

Since

2.0.14

protected function getUrlFromCache(string $cacheKey, string $route, array $params): bool|string

Get URL from internal cache if exists.

Parameters

ParameterTypeDescription
$cacheKeystringGenerated cache key to store data.
$routestringThe route (e.g. site/index).
$paramsarrayRule params.

Returns

bool|string: The created URL

Since

2.0.8

See also

protected function setBuiltRulesCache(array $ruleDeclarations, yii\web\UrlRuleInterface[] $builtRules): bool

Stores $builtRules to cache, using $rulesDeclaration as a part of cache key.

Parameters

ParameterTypeDescription
$ruleDeclarationsarrayThe rule declarations. Each array element represents a single rule declaration. Please refer to $rules for the acceptable rule formats.
$builtRulesUrlRuleInterface[]The rule objects built from the given rule declarations.

Returns

bool: Whether the value is successfully stored into cache

Since

2.0.14

protected function setRuleToCache(mixed $cacheKey, yii\web\UrlRuleInterface $rule): mixed

Store rule (e.g. UrlRule) to internal cache.

Parameters

ParameterTypeDescription
$cacheKeymixed
$ruleUrlRuleInterface

Returns

mixed

Since

2.0.8