- Yii2 Framework
-
Introduction & Setup
- Introduction to Yii2 Framework
- Installing Yii2 (Basic & Advanced Templates)
- Understanding Yii2 Directory Structure
- Yii2 Configuration Basics
- Routing & Pretty URLs in Yii2
-
Yii2 Core Concepts
- Yii2 Application Bootstrapping & Lifecycle
- Understanding Yii2 Request & Response Handling
- Working with Yii2 Components & Helpers
- Yii2 Widgets & Using Built-in Widgets
- Yii2 Helpers & Utility Classes
-
Models & Database Operations
- Yii2 Models, Active Record & Database Connections
- CRUD Operations in Yii2
- Yii2 Query Builder & DAO (Direct SQL Queries)
- Handling Relationships in Yii2 Active Record
- Yii2 Migrations & Seeding
-
Views, Layouts & Themes
- Yii2 Views & Layouts
- Yii2 Asset Bundles & Asset Management
- Integrating Bootstrap in Yii2
- Yii2 Theme Integration
- Yii2 Custom Widgets & Reusable Components
-
Forms, Validation & Data Presentation
- Yii2 Forms & Validation
- Using Yii2 GridView & ListView Widgets
- Yii2 Pagination & Sorting
- Yii2 File Uploads
-
Security & User Management
- User Authentication in Yii2
- Role-Based Access Control (RBAC) in Yii2
- Yii2 Security Features
-
Console Commands & Advanced Features
- Yii2 Console Commands
- Yii2 Events & Behaviors
- Yii2 RESTful API Development
- Consuming Third-Party APIs in Yii2
- Yii2 Background Jobs & Queue System
-
Performance Optimization & Caching
- Yii2 Caching Techniques
- Yii2 Performance Optimization
- Debugging & Logging in Yii2
-
Deployment & Best Practices
- Deploying Yii2 Applications
- Yii2 Best Practices & Large-Scale Application Structure
- Yii2 Multilingual & Localization Support
- Yii2 Module Development
- Integrating Yii2 with Frontend Frameworks (Angular/Vue/React)
-
Special Topics
- Dependency Injection (DI) in Yii2
Routing & Pretty URLs in Yii2
Introduction
Routing in Yii2 is responsible for processing incoming requests and mapping them to the appropriate controllers and actions. Yii2 provides a flexible and powerful routing system, allowing clean URLs (Pretty URLs) and custom route configurations. In this tutorial, we will cover:
- How Yii2 handles routing
- Enabling Pretty URLs
- Customizing routes
- Using parameterized routes
- Creating URL rules
- Routing for Yii2 Modules
- Generating URLs using
Url::to()
andUrl::toRoute()
1. Understanding Routing in Yii2
In Yii2, routing is managed by the urlManager
component. When a user visits a URL, Yii2 processes the request and determines which controller and action should handle it.
For example, visiting:
http://yourwebsite.com/index.php?r=site/about
Maps to:
- Controller:
SiteController
(controllers/SiteController.php
) - Action:
actionAbout()
By default, Yii2 uses query parameters (?r=controller/action
). To improve readability, we enable Pretty URLs.
2. Enabling Pretty URLs
Pretty URLs remove the ?r=
parameter, making URLs more user-friendly.
Step 1: Modify config/web.php
(Basic Template)
'components' => [
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
// Define custom rules here
],
],
],
enablePrettyUrl
→ Enables clean URLsshowScriptName
→ Hidesindex.php
from URLs
For Advanced Template
Modify frontend/config/main.php
and backend/config/main.php
in the same way.
3. Creating Custom Routes
Custom routes allow defining user-friendly URLs. Add route rules inside urlManager['rules']
.
'rules' => [
'about-us' => 'site/about', // Maps "about-us" to "site/about"
'contact' => 'site/contact', // Maps "contact" to "site/contact"
]
Now,
http://yourwebsite.com/about-us
4. Using Parameterized Routes
Routes can include dynamic parameters. Example:
'rules' => [
'post/<id:\d+>' => 'post/view', // Maps "post/123" to "post/view?id=123"
],
Here, \d+
ensures only numeric values are accepted.
If a user visits:
http://yourwebsite.com/post/5
It will be mapped to:
http://yourwebsite.com/index.php?r=post/view&id=5
Without the ?id=5
query string.
5. Generating URLs Using Url::to()
When creating links in Yii2, use Url::to()
:
use yii\helpers\Url;
<a href="<?= Url::to(['site/about']) ?>">About</a>
This ensures URLs are generated correctly, even if route structures change.
For dynamic parameters:
<?= Url::to(['post/view', 'id' => 5]) ?>
Generates /post/5
when Pretty URLs are enabled.
6. Routing for Yii2 Modules
Modules are like mini-applications within Yii2. If you're using modules, you need to set up routing correctly.
Step 1: Define Modules in Configuration
Modify config/web.php
to register modules:
'modules' => [
'admin' => [
'class' => 'app\modules\admin\Module',
],
],
Here, we register an admin
module located at modules/admin/Module.php
.
Step 2: Accessing Module Routes
By default, Yii2 maps module routes as:
http://yourwebsite.com/index.php?r=admin/default/index
Which means:
- Module:
admin
- Controller:
DefaultController
(modules/admin/controllers/DefaultController.php
) - Action:
actionIndex()
If Pretty URLs are enabled, visiting:
http://yourwebsite.com/admin
Will map to admin/default/index
.
Step 3: Custom Pretty URLs for Modules
Modify config/web.php
inside urlManager
:
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'admin' => 'admin/default/index',
'admin/<controller>/<action>' => 'admin/<controller>/<action>',
],
],
Now,
Will map to:
- Module:
admin
- Controller:
UserController
(modules/admin/controllers/UserController.php
) - Action:
actionList()
Step 4: Generating URLs for Modules
Inside your views or controllers, generate module URLs like this:
<?= Url::to(['/admin/user/list']) ?>
This will generate:
http://yourwebsite.com/admin/user/list
7. Generating URLs Using Url::to()
and Url::toRoute()
Yii2 provides two primary methods for generating URLs dynamically:
7.1 Using Url::to()
The Url::to()
function is useful when generating absolute and relative URLs.
Basic Example
use yii\helpers\Url;
echo Url::to(['site/about']);
This will generate:
/index.php?r=site/about
Or, if Pretty URLs are enabled:
/site/about
Generating URLs with Parameters
echo Url::to(['post/view', 'id' => 10]);
This will generate:
/post/view?id=10
Or with Pretty URLs:
/post/10
Generating Absolute URLs
echo Url::to(['site/about'], true);
Generates:
http://yourwebsite.com/site/about
7.2 Using Url::toRoute()
(Why It’s Important!)
Url::toRoute()
is more flexible and ensures the URL is generated relative to the current module and controller.
Basic Example
echo Url::toRoute(['site/about']);
This works similarly to Url::to()
but is useful in modular applications.
Generating URLs Within Modules
If you're inside a module and use Url::to()
, it may not correctly generate module-specific routes. Instead, use Url::toRoute()
:
echo Url::toRoute(['/admin/user/list']);
This ensures it correctly generates the module-based URL:
http://yourwebsite.com/admin/user/list
Key Differences Between Url::to()
and Url::toRoute()
Feature | Url::to() | Url::toRoute() |
---|---|---|
Generates absolute URL | (when true passed) | No |
Works with module-specific routes | No | Yes |
Good for general URLs | Yes | Yes |
Good for module-based routing | No | Yes |
Uses current module & controller | No | Yes |
8. Handling 404 Errors for Undefined Routes
If a route is not found, Yii2 automatically shows a 404 error. To customize this, modify views/site/error.php
.
<h1><?= $name ?></h1>
<p><?= nl2br(Html::encode($message)) ?></p>
You can also log undefined routes by customizing errorHandler
.
9. Testing and Verifying Pretty URLs
Clear Cache: Run
php yii cache/flush-all
Check .htaccess
(For Apache)
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
Restart Web Server (For Nginx/Apache)
Conclusion
Yii2 routing system provides flexibility to define clean and SEO-friendly URLs. We covered:
- Enabling Pretty URLs
- Defining custom routes
- Handling dynamic parameters
- Generating links using
Url::to()
- Setting up routes for Yii2 Modules
- Generating URLs using
Url::to()
andUrl::toRoute()
Now, your Yii2 app will have professional and user-friendly URLs. In the next tutorial, we will explore Yii2 Controllers & Actions!
Prepare for Interview
- Debugging in Python
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
- Generators in Python
- Requests in Python
- Django
- Flask
- Matplotlib/Seaborn
- Pandas
- NumPy
- Modules and Packages in Python
- File Handling in Python
- Error Handling and Exceptions in Python
- Indexing and Performance Optimization in SQL
Random Blogs
- Mastering Python in 2025: A Complete Roadmap for Beginners
- Datasets for Natural Language Processing
- String Operations in Python
- Types of Numbers in Python
- 5 Ways Use Jupyter Notebook Online Free of Cost
- Extract RGB Color From a Image Using CV2
- AI in Cybersecurity: The Future of Digital Protection
- How AI is Making Humans Weaker – The Hidden Impact of Artificial Intelligence
- The Ultimate Guide to Data Science: Everything You Need to Know
- The Ultimate Guide to Artificial Intelligence (AI) for Beginners
- Role of Digital Marketing Services to Uplift Online business of Company and Beat Its Competitors
- Google’s Core Update in May 2020: What You Need to Know
- Career Guide: Natural Language Processing (NLP)
- 10 Awesome Data Science Blogs To Check Out
- Generative AI - The Future of Artificial Intelligence
Datasets for Machine Learning
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset
- Bitcoin Heist Ransomware Address Dataset