Skip to main content

Installation

Get FastRoute up and running in your project in just a few minutes.

Requirements

FastRoute requires PHP 5.4.0 or higher. For best performance, use PHP 7.4 or later.

Installing with Composer

1

Ensure Composer is Installed

Make sure you have Composer installed on your system. Verify by running:
composer --version
If Composer is not installed, follow the official installation guide.
2

Create composer.json

In your project root directory, create a composer.json file with the FastRoute dependency:
composer.json
{
    "require": {
        "nikic/fast-route": "^1.3"
    }
}
The ^1.3 version constraint ensures you get the latest 1.x version with bug fixes and improvements while maintaining compatibility.
3

Install Dependencies

Run Composer to install FastRoute and its dependencies:
composer install
This will create a vendor directory containing FastRoute and Composer’s autoloader.
4

Set Up Autoloading

In your main PHP file (e.g., index.php), require Composer’s autoloader:
index.php
<?php

// Autoload Composer dependencies
require 'vendor/autoload.php';

// Your routing code will go here
This makes all Composer packages, including FastRoute, available in your application.

Project Structure

For better organization, we recommend structuring your project like this:
project-root/
├── vendor/              # Composer dependencies
├── routes/              # Route definition files
│   ├── api.php         # API routes
│   └── web.php         # Web routes
├── views/              # View templates
├── composer.json       # Composer configuration
└── index.php          # Main entry point
Separating routes into different files (API and web) makes your application more maintainable and easier to scale.

Web Server Configuration

FastRoute requires URL rewriting to route all requests through your main PHP file.

Apache Configuration

Create an .htaccess file in your project root:
.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]
For Apache, you must enable AllowOverride All in your virtual host configuration:
/etc/apache2/sites-available/000-default.conf
<Directory /var/www/html>
    AllowOverride All
</Directory>
Then restart Apache: sudo systemctl restart apache2

Nginx Configuration

Add this to your Nginx server block:
location / {
    try_files $uri $uri/ /index.php?$query_string;
}

Verification

To verify the installation, create a simple test in your index.php:
index.php
<?php

require 'vendor/autoload.php';

use FastRoute\RouteCollector;

$dispatcher = FastRoute\simpleDispatcher(function(RouteCollector $r) {
    $r->get('/test', function() {
        echo "FastRoute is working!";
    });
});

echo "Installation successful!";
If you see “Installation successful!” when accessing your site, FastRoute is ready to use.

Next Steps

Now that FastRoute is installed, let’s create your first routes in the Quickstart Guide.