CodeIgniter Q & A

 

How to implement user-friendly URLs in CodeIgniter?

Implementing user-friendly URLs, often referred to as “clean” or “semantic” URLs, is essential for improving the readability and search engine optimization (SEO) of your CodeIgniter application. CodeIgniter provides a convenient way to achieve this using its routing system. Here’s how you can implement user-friendly URLs in CodeIgniter:

 

  1. Configure Routes: In CodeIgniter, routing is defined in the `routes.php` configuration file located in the `application/config` directory. You can set up custom routes that map user-friendly URLs to specific controller methods. For example, if you want to make the URL `example.com/products` map to a `Products` controller’s `index` method, you can define the route like this:

 

   ```php

   $route['products'] = 'Products';

   ```

 

   This tells CodeIgniter to route requests to `/products` to the `Products` controller without explicitly specifying the `index` method.

 

  1. Enable Query Strings: By default, CodeIgniter uses URLs with query strings to pass parameters to controller methods, such as `example.com/controller/method/param1/param2`. However, you can enable “query strings” in the `config.php` file (located in `application/config`) by setting the `enable_query_strings` option to `TRUE`. This allows you to use URLs like `example.com/controller/method?param1=value1&param2=value2`. To enable query strings, add this line to your `config.php`:

 

 ```php

   $config['enable_query_strings'] = TRUE;

   ```

 

  1. Use .htaccess: To create cleaner URLs without query strings and remove the `index.php` segment from your URLs, you can utilize an `.htaccess` file (Apache server). Place an `.htaccess` file in your CodeIgniter project’s root directory with the following content:

 

  ```

   RewriteEngine On

   RewriteCond %{REQUEST_FILENAME} !-f

   RewriteCond %{REQUEST_FILENAME} !-d

   RewriteRule ^(.*)$ index.php/\ [L]

   ```

 

   This configuration allows you to use URLs like `example.com/controller/method/param1/param2` instead of `example.com/index.php/controller/method/param1/param2`.

 

  1. Controller and Method Naming:  Ensure that your controller and method names follow a clear and user-friendly structure that corresponds to the content or functionality they represent. This helps maintain consistency and readability in your URLs.

 

By configuring custom routes, enabling query strings (if desired), and using an `.htaccess` file, you can implement user-friendly URLs in your CodeIgniter application. These clean URLs not only enhance user experience but also improve SEO by making your website’s structure more accessible and understandable to both users and search engines.

Previously at
Flag Argentina
Brazil
time icon
GMT-3
Experienced Full Stack Systems Analyst, Proficient in CodeIgniter with extensive 5+ years experience. Strong in SQL, Git, Agile.