In Yii, routes map URLs to controller actions for clean and SEO-friendly links. By default, URLs follow the pattern controllerID/actionID, but custom routes can be defined in config/web.php using the urlManager. Steps include enabling pretty URLs, defining rules like 'post/
In Yii, routes are essentially the mapping between URLs and the corresponding controller actions that handle them. They help determine which part of your application should respond when a specific URL is accessed. Defining routes properly is important for clean URLs, better user experience, and SEO-friendly links.
Understanding How Routes Work in Yii
By default, Yii uses a built-in routing system that maps URLs to controllers and actions using a pattern like this:
http://example.com/index.php?r=controllerID/actionID
Here, r
stands for route, and it follows the format ControllerID/ActionID
. For example, if you have a PostController
with an action view
, the URL might look like:
http://example.com/index.php?r=post/view&id=105
This works fine out of the box, but for cleaner and more readable URLs, you’ll want to define custom routes.
Defining Custom Routes in Yii
To make URLs prettier and easier to remember (like /post/view/105
or even /post/105
), you need to configure URL rules in your application’s configuration file (config/web.php
).
Here’s how you can define a simple custom route:
'urlManager' => [ 'enablePrettyUrl' => true, 'showScriptName' => false, 'rules' => [ 'post/<id:\d >' => 'post/view', ], ],
What this does:
- Enables pretty URLs (removes
index.php
from the URL). - Maps
/post/105
to theview
action of thePostController
, passingid=105
.
You can also define more complex patterns, such as dynamic slugs:
'article/<slug:[a-zA-Z0-9\-_] >' => 'article/view',
This would match URLs like /article/my-first-post
and pass the slug to the controller.
Common Mistakes and Tips When Defining Routes
When working with routes in Yii, here are some common issues and tips to avoid them:
- Make sure
enablePrettyUrl
is set totrue
, otherwise custom rules won’t work. - Check
.htaccess
– If you're using Apache, ensure you have a proper.htaccess
file to hideindex.php
. - Order matters – Rules are matched top to bottom, so place more specific rules before general ones.
- Use named parameters wisely – Like
<id:\d >
or<slug:\w >
to validate input right in the route. - Test your routes – Use tools like
Url::to()
in views to generate correct links based on your defined routes.
If you’re not seeing expected behavior, double-check the config file and clear the cache.
Handling Fallbacks and 404 Pages
Sometimes a route doesn't match any defined rule. In those cases, Yii will throw a 404 error by default. You can customize this behavior if needed.
For example, you might want to log unmatched routes or redirect users to a homepage:
'on urlManagerParseError' => function ($event) { // Log or redirect Yii::$app->response->redirect(['site/index'])->send(); $event->handled = true; },
This kind of customization helps improve user experience when someone hits a broken or unknown link.
Basically, routes in Yii are about translating URLs into actions. Whether you stick with the default system or go all-in on custom rules, understanding how to define and manage them gives you control over your app's URL structure. It's not complicated, but it's easy to overlook small details like rule order or regex patterns.
The above is the detailed content of What are routes in Yii, and how are they defined?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Apache Camel is an Enterprise Service Bus (ESB)-based integration framework that can easily integrate disparate applications, services, and data sources to automate complex business processes. ApacheCamel uses route-based configuration to easily define and manage integration processes. Key features of ApacheCamel include: Flexibility: ApacheCamel can be easily integrated with a variety of applications, services, and data sources. It supports multiple protocols, including HTTP, JMS, SOAP, FTP, etc. Efficiency: ApacheCamel is very efficient, it can handle a large number of messages. It uses an asynchronous messaging mechanism, which improves performance. Expandable

Tips for using route interceptors in uniapp In uniapp development, route interceptors are a very common function. Route interceptors allow us to perform some specific operations before routing jumps, such as permission verification, page passing parameters, etc. In this article, we will introduce the tips for using route interceptors in uniapp and provide specific code examples. Create a route interceptor First, we need to create a route interceptor in the uniapp project. The creation method is as follows: Create an inter in the project root directory

The main differences between Laravel and Yii are design concepts, functional characteristics and usage scenarios. 1.Laravel focuses on the simplicity and pleasure of development, and provides rich functions such as EloquentORM and Artisan tools, suitable for rapid development and beginners. 2.Yii emphasizes performance and efficiency, is suitable for high-load applications, and provides efficient ActiveRecord and cache systems, but has a steep learning curve.

The steps to containerize and deploy Yii applications using Docker include: 1. Create a Dockerfile and define the image building process; 2. Use DockerCompose to launch Yii applications and MySQL database; 3. Optimize image size and performance. This involves not only specific technical operations, but also understanding the working principles and best practices of Dockerfile to ensure efficient and reliable deployment.

In Golang, using functions to handle web request routing is an extensible and modular method of building APIs. It involves the following steps: Install the HTTP router library. Create a router. Define path patterns and handler functions for routes. Write handler functions to handle requests and return responses. Run the router using an HTTP server. This process allows for a modular approach when handling incoming requests, improving reusability, maintainability, and testability.

Migratingalaravel Projecttoyiiishallingbutachieffable WITHIEFLEFLANT.1) Mapoutlaravel component likeroutes, Controllers, Andmodels.2) Translatelaravel's SartisancommandeloequentTooyii's giiandetiverecordeba

How to use routing in uni-app for page jumps In uni-app development, routing is one of the most commonly used functions. By using routing, we can jump between pages to achieve a good user experience. This article will introduce how to use routing to jump to pages in uni-app, and provide specific code examples for reference. First, we need to understand the routing mechanism in uni-app. The routing mechanism of uni-app is encapsulated using vue-router, so we can use vu

The main difference between senior Yii developers and junior Yii developers is experience, depth of skills and way of thinking. 1. Senior developers pay attention to performance optimization and code reconstruction, and use Yii's cache mechanism to improve application performance. 2. They deeply understand Yii's underlying principles, participate in architectural design and technical decision-making, and use modular design to build flexible applications. 3. Senior developers pay attention to overall project planning and long-term development and play the role of mentor. Junior developers need to gradually improve through learning and practice, and eventually grow into senior developers.
