- 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
Add to BookmarkIntroduction
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/aboutMaps 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.phpfrom 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-us4. 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/5It will be mapped to:
http://yourwebsite.com/index.php?r=post/view&id=5Without 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/indexWhich means:
- Module:
admin - Controller:
DefaultController(modules/admin/controllers/DefaultController.php) - Action:
actionIndex()
If Pretty URLs are enabled, visiting:
http://yourwebsite.com/adminWill 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/list7. 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/aboutOr, if Pretty URLs are enabled:
/site/aboutGenerating URLs with Parameters
echo Url::to(['post/view', 'id' => 10]);This will generate:
/post/view?id=10Or with Pretty URLs:
/post/10Generating Absolute URLs
echo Url::to(['site/about'], true);Generates:
http://yourwebsite.com/site/about7.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/listKey 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-allCheck .htaccess (For Apache)
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.phpRestart 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
- JavaScript Interview Questions for 5+ Years Experience
- JavaScript Interview Questions for 2–5 Years Experience
- JavaScript Interview Questions for 1–2 Years Experience
- JavaScript Interview Questions for 0–1 Year Experience
- JavaScript Interview Questions For Fresher
- SQL Interview Questions for 5+ Years Experience
- SQL Interview Questions for 2–5 Years Experience
- SQL Interview Questions for 1–2 Years Experience
- SQL Interview Questions for 0–1 Year Experience
- SQL Interview Questions for Freshers
- Design Patterns in Python
- Dynamic Programming and Recursion in Python
- Trees and Graphs in Python
- Linked Lists, Stacks, and Queues in Python
- Sorting and Searching in Python
Random Blogs
- Where to Find Free Datasets for Your Next Machine Learning & Data Science Project
- Store Data Into CSV File Using Python Tkinter GUI Library
- AI & Space Exploration – AI’s Role in Deep Space Missions and Planetary Research
- 15 Amazing Keyword Research Tools You Should Explore
- Mastering SQL in 2025: A Complete Roadmap for Beginners
- Top 10 Knowledge for Machine Learning & Data Science Students
- Why to learn Digital Marketing?
- Datasets for Speech Recognition Analysis
- Transforming Logistics: The Power of AI in Supply Chain Management
- Extract RGB Color From a Image Using CV2
- Quantum AI – The Future of AI Powered by Quantum Computing
- Understanding Data Lake, Data Warehouse, Data Mart, and Data Lakehouse – And Why We Need Them
- Loan Default Prediction Project Using Machine Learning
- AI is Replacing Search Engines: The Future of Online Search
- Create Virtual Host for Nginx on Ubuntu (For Yii2 Basic & Advanced Templates)
Datasets for Machine Learning
- Awesome-ChatGPT-Prompts
- Amazon Product Reviews Dataset
- 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

