Custom Domains And Basic Routing In Yii2

Custom Domains And Basic Routing In Yii2

Next up in our Yii Tutorial Series is to look at setting up a basic development environment for working with Yii2 on your local machine. When we originally created the basic application skeleton that Yii provides, we placed it into it’s own folder. In order to access our site, we had to visit something like http://localhost/yii/basic/web/ which is fine, but a bit cumbersome. Instead, we can set up something cool like and have it point right to our local server. Once we do this, we’ll take a quick look at how Yii handles requests and maps them to routes. This is the main purpose of a web application, to respond to requests from users, so we need to understand how that works. Let’s jump in.

Creating Your Custom Domain

No need to go out and spend any money at your favorite registrar, for this episode, we’re simply going to set up our own domain name on the local machine. These steps were carried out using Windows 7 with a wamp installation. Why wamp? One click installation, and devops is not fun. Who wants to tinker with virtual machines all day long? They do have their place, and once this eventually becomes a one click scenario, it may be worth a look. Enough of that however, let’s get started.

Step 1. Edit your hosts file.

Navigate to C:WindowsSystem32driversetc and open the hosts file. You will need to use Notepad in Administrative Mode to do this by following All Programs->Accessories-> right click ‘notepad’ and ‘Run as Administrator’. If you do not use Notepad as administrator, you’ll get an error message like Access is Denied. Once you have the hosts file open in Notepad as administrator, you should see a line in the file that looks like this. localhost

This is what allows you to type in localhost into your web browser instead of What you can do is add your own domain to this file, so that you have a nicer local development experience. If you’d like to use you can simply add this line to the file, then save it. Close out the hosts file once complete.

Step 2. Edit The Apache Virtual Hosts Configuration

Find the httpd-vhosts.conf file which would be located somewhere like C:wampbinapacheApache2.4.9confextra. You’ll need to add the following snippet to the end of the file.

<VirtualHost *:80>
DocumentRoot “C:/wamp/www/yii/basic/web”

<VirtualHost *:80>
DocumentRoot “C:/wamp/www”
ServerName localhost

Important! The first entry is mapping to the folder where your Yii application lives. If you named your application something different, or it is located elsewhere, be sure to update the DocumentRoot with the correct location of your Yii web root folder. In addition, your ServerName can be whatever you want, it doesn’t have to be You could use or whatever you like. Just be aware that if it is an actual domain name that lives out on the internet, you will no longer be able to visit that domain from your machine, since you hacked the hosts file to point that domain to

The second entry is important to have so that you can continue to also use localhost if you like. If this line is not included, you’ll lose the ability to use localhost once we turn on Virtual Hosts on Apache.

Step 3. Turn on Apache Virtual Hosts

The last thing we need to do is to turn on virtual hosts in Apache. For this, we need to open httpd.conf which would be located somewhere like C:wampbinapacheApache2.4.9conf. Look for the line # Include conf/extra/httpd-vhosts.conf and simply change it by removing the leading hashtag # like so Include conf/extra/httpd-vhosts.conf This tells Apache to make use of that virtual hosts configuration we just completed in Step 2. Now you need to restart all services. Once everything restarts, you are now rocking and rolling at

Yii Routing

First off, let’s direct you to a great resource if you’re new to learning Yii. Of course, your best resource is the official Yii API documentation which has quick links to their definitive guide as well as the class reference and additional extensions. Another great resource is a great book by Bill Keck who maintains a blog about Yii. You can get the book at leanpub right here. It’s a great resource because it takes the perspective of someone who is new to the framework and is diving in with a self learning crash course in getting things working with Yii. This real world approach is valuable in learning the key concepts when the rubber hits the road so to speak.

Enter Here

When users make a request of a Yii powered site, they will be hitting the index.php script first. With our handy setup, that will be You can load that right up, and Yii will load a page just fine. It does this even without specifying a route. How does it do this? This is because the basic application in Yii has a default route set for you for this very purpose. In no route is provided, Yii will go to site/index since this is what is configured in the core of Yii. This can easily be overridden in the config file by adding a key / value pair to the config array. Let’s see how.

config/web.php source

This is just the snippet of the top of the web.php file. Notice we added that first key value pair with a comma after it 'defaultRoute' => 'drums', which specifies that the DrumsController.php is now the default controller. What about the action? Again by default, this will use the actionIndex method so by not specifying the action portion of the route in the config, what you are really saying is to use drums/index as the default route. You can also specify the action portion of the default route like so

config/web.php source

This will run the actionCreate method of the DrumsController.php when you simply load the home page with no routes specified. We can prove this by loading up and see this output.
yii configure default route

This is pretty cool, but we’re going to remove that from the config file. We just wanted to demonstrate how to configure the Yii default route.


This brings us to the main idea with basic routing in Yii, and that is the controller / action pair. By simply looking at the URL, we can determine what the controller and action being invoked is. From our prior example of running Gii and creating CRUD for our drums, the association looks like this.

URL Requested Controller / Method DrumsController / actionCreate DrumsController / actionIndex DrumsController / actionUpdate DrumsController / actionDelete

These associations are passed in the URL to a parameter named simply, r. This is the GET superglobal so in raw php it would be something like $_GET['r']. In Yii, this r parameter will be assigned the controller / action pair. It may also just contain the controller. For example, this url is simply passing drums as a value to the r query parameter. Yii inspects this and says, “Oh, this is the actionIndex method on the DrumsController” and sends the request on it’s way.

Passing Parameters

Sometimes a controller action pair will require a parameter to be passed, and if one is not, the call to that method will fail. Some of the methods we have looked at so far that will require a parameter include actionView($id), actionUpdate($id), and actionDelete($id). This is because we are taking direct action on a single piece of data, so we need to identify which data that is. This is almost always done by using a row’s unique id. Let’s test it. Say we load Our application is not going to like us very much because it has no way of knowing what data to update. You’ll get an error like this:

Bad Request (#400)

Missing required parameters: id

The above error occurred while the Web server was processing your request.

Please contact us if you think this is a server error. Thank you.

Now errors like this are never fun, so lets just make sure to pass the proper parameters. If on the other hand we load this URL,, everything will be just fine since we are identifying what data needs to be updated. In this case, it is the row with an id of 1. You can have several parameters passed in the query string, just like normal php.

Generating Links With Yii

In any website, we are going to need links. Links for navigation, links for linking to external resources, and more. If you lean more to the design side of things rather than development, you’ll have the urge to start building links by hand in your web applications. Resist this urge! Instead of creating links by hand when using Yii, we should be using something like createAbsoluteUrl() or one of the many other ways to generate links and URLs. Why? The reason is because your application becomes more fragile and less portable. Just like in php itself, there are many, many ways to accomplish the same goal when building something. We’ll look at this one, as well as using the yiihelpersHtml class since this is what the Gii tool generates, and seems to be quite slick. Let’s see how each of these work:

There are a few things to note here. It looks like the preferred way to do this would be to use the yiihelpersHtml class since it easily builds the full link for you. The yiiwebUrlManager approach would be better suited for situation where you may need more granular control over how to assemble a link or URL in the application.

Pretty URLS in Yii

Last up in this episode is a quick overview of how to turn on pretty URLs in Yii. It makes sense to leave pretty URLs turned off during the entire development of your application. You may even want to deploy to production with pretty URLs turned off. Why? Well for one, pretty URLs are over rated. Two, pretty URLs add another layer of complexity to the development environment and when we’re developing, we want to minimize potential gotchas, not increase them. When you’re ready however, this is how we do it.

Step 1. Make sure Apache rewrite_module is enabled.

If you do all of the following steps correctly, you may start going crazy trying to figure out why pretty URLs are not working. Make sure this first step is taken care of to save your sanity!

Step 2. Update Configuration for URL Manager.

Navigate to config/web.php and update the configuration. It may look a bit like this, note the addition of urlManager to the components array.

config/web.php source

Step 3. Create This .htaccess file

You’ll need to create this .htaccess file and place it in your web directory.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php

Now you can visit URLs like this instead of this Note that additional parameters will still be passed as query strings at this point. For example, this will not work yet but this will Basically, once you turn on pretty URLs, you are going to need to dive into setting up rules in your urlManager. This requires knowledge of regular expressions which are infamous for being tricky to decipher. This is why, during development, just leave the base routing in place. It will make troubleshooting easier.

config/web.php source

Note the rule: <controller:(drums)>/<action:(update|view)>/<id:d+>’ => ‘<controller>/<action>

This will now allow us to use urls like or This is an example of a parameterized route which allows you to specify multiple controller and action names in one line. This one is simple, it just says any time you use the drums controller, with either the update or view actions followed by a numeric number as an id, it will register as a valid route. In some ways, its pretty straight forward, but it can be tricky to troubleshoot.


In this episode we took a look at how to set up a custom domain name when building an application with Yii. Then we had a look at the basics of how routing works with Yii and setting a default route in addition to turning on pretty URLs if we like. Make sure to read the official guide at the Yii website for further details.