Skip to main content
PHP Backend Development Tutorial
CHAPTER 13 Beginner

Routing and URL Management

Updated: May 14, 2026
20 min read

# CHAPTER 13

Routing and URL Management

1. Introduction

If you look at the URL of a modern website (like github.com/john/repo), you will notice there is no .php at the end. Modern web applications do not map URLs to physical files on the server. Instead, they use a centralized Router. In this chapter, we will learn how to intercept all incoming web traffic and direct it through a single "Front Controller," creating clean, SEO-friendly, and highly secure URLs.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Explain the concept of a Front Controller pattern.
  • Configure an Apache .htaccess file to rewrite URLs.
  • Build a custom PHP Router from scratch.
  • Handle dynamic URL parameters (e.g., /user/5).

3. Beginner-Friendly Explanation

Imagine an old-fashioned office building. If you want to talk to Bob in Accounting, you walk straight to Room 302 and open the door. (This is old PHP: www.site.com/accounting/bob.php). But what if Bob moves? What if you shouldn't be in that room? A modern office has a Receptionist in the lobby. Everyone who enters the building *must* talk to the receptionist. You say, "I want Bob." The receptionist checks your ID, finds Bob's current location, and safely escorts you there. In modern PHP, the Router is the receptionist. Every single URL request goes to one single file (index.php), which acts as a traffic cop and directs the request to the right code.

4. The Magic of .htaccess (Apache Rewrite)

To force all traffic to go to a single index.php file, we must tell the Apache Web Server to rewrite the rules. We do this by creating a hidden file named .htaccess in the root of our project.

.htaccess

apache
123456
RewriteEngine On
# If the requested URL is not an actual physical file or folder...
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# ...send all traffic to index.php
RewriteRule ^(.*)$ index.php [QSA,L]

Now, if a user types localhost/myproject/about, Apache will silently load index.php instead of looking for an about.php file.

5. Building a Basic Router

Now that all traffic is flowing into index.php, we can use PHP to look at the URL the user typed and decide what code to run.

index.php (The Front Controller)

php
1234567891011121314151617181920212223242526
<?php
// Get the URL the user typed
$request = $_SERVER[&#039;REQUEST_URI'];

// Remove the base project path (adjust based on your setup)
$uri = str_replace(&#039;/myproject/', '/', $request);

// The Router Logic (Switch Statement)
switch ($uri) {
    case &#039;/':
        echo "<h1>Home Page</h1>";
        break;
    case &#039;/about':
        echo "<h1>About Us</h1>";
        // In a real app, we would include a file here: require 'views/about.php';
        break;
    case &#039;/contact':
        echo "<h1>Contact Us</h1>";
        break;
    default:
        // Handle 404 Not Found
        http_response_code(404);
        echo "<h1>404 Error: Page Not Found</h1>";
        break;
}
?>

6. Dynamic URL Parameters

What if we have an e-commerce site with 10,000 products? We can't write a switch statement for every product. We need a "Dynamic Route" (e.g., /product/55).
php
1234567891011121314
<?php
$uri = $_SERVER[&#039;REQUEST_URI'];

// Use Regular Expressions to match a pattern
// This matches "/product/ANY_NUMBER"
if (preg_match(&#039;/^\/product\/([0-9]+)$/', $uri, $matches)) {
    
    // $matches[1] will hold the number the user typed in the URL
    $product_id = $matches[1];
    
    echo "<h1>Viewing Product ID: " . $product_id . "</h1>";
    // Here, you would query the database for Product #$product_id
}
?>

7. Why Use a Router?

  1. 1. Clean URLs: /users/profile looks much better and ranks higher on Google than /profile.php?userid=5&action=view.
  1. 2. Centralized Security: Because every request passes through index.php, you can put your database connection and session start code at the very top. You never have to copy-paste sessionstart() into 50 different files ever again.
  1. 3. Hide File Structure: Hackers cannot guess the names of your physical server files because the URLs do not map to files anymore.

8. Backend Workflow: API Routing

Modern APIs heavily utilize routing. If a mobile app sends a GET request to /api/users, the router triggers a function to fetch all users. If it sends a DELETE request to /api/users/5, the router triggers a function to delete user 5.

9. Best Practices

  • Use a Routing Library: While building a router from scratch is a great learning exercise, professional applications use established routing packages (like bramus/router or Laravel's built-in router) which handle complex regular expressions and HTTP methods automatically.

10. Common Mistakes

  • Forgetting the .htaccess File: If you write a beautiful index.php router, but you click a link to /about and get a server-level "404 Not Found" error, it means Apache doesn't know it's supposed to route traffic to index.php. You must configure .htaccess or the Nginx equivalent.

11. Exercises

  1. 1. Explain the "Front Controller" design pattern and how it improves application security.

12. Coding Challenges

  • Challenge: Expand the basic router switch statement to include an /admin route. If the user visits /admin, write an if statement to check if a hypothetical $SESSION['isadmin'] is true. If not, output "Access Denied."

13. MCQs with Answers

Question 1

What is the primary purpose of configuring an .htaccess file when building a custom PHP router?

Question 2

Why are "Clean URLs" (like /blog/php-tutorial instead of /article.php?id=12) preferred in modern web development?

14. Interview Questions

  • Q: Describe how you would implement a dynamic route (e.g., /user/{id}) in a custom PHP router without using a framework.
  • Q: What is the Front Controller pattern, and what are the architectural benefits of funneling all web traffic through a single entry point?

15. FAQs

Q: Do I have to write my own router if I use a framework like Laravel? A: No! Modern frameworks handle all of this under the hood. In Laravel, you simply define a route in a specific file: Route::get('/about', function() { return view('about'); });. The framework does the heavy lifting.

16. Summary

In Chapter 13, we took control of our application's traffic. By configuring our web server with .htaccess and building a centralized Front Controller (index.php), we separated our URLs from our physical file structure. This allows us to create beautiful, SEO-friendly routes, intercept unauthorized access efficiently, and gracefully handle dynamic URL parameters, stepping firmly into professional application architecture.

17. Next Chapter Recommendation

Routing solves URL management, but our code is still messy. We need to separate our database queries from our HTML. Proceed to Chapter 14: MVC Architecture in PHP.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·