This PHP router is designed with dual compatibility to work seamlessly in both development and production environments without code changes.
The router automatically detects its environment and adapts its behavior:
# Start the PHP built-in development server php -S localhost:8000 router.php
In development mode, the router uses PHP's built-in server capabilities:
// Check if it's a static file (needed for PHP built-in server compatibility)
$file = __DIR__ . $uri;
if (is_file($file)) {
return false; // Let PHP's built-in server handle static files
}
# Enable mod_rewrite
sudo a2enmod rewrite
sudo systemctl restart apache2
# In your virtual host or apache2.conf:
<Directory /var/www/html>
AllowOverride All
Require all granted
</Directory>
RewriteEngine On
# If the requested file doesn't exist AND the requested directory doesn't exist
# then route the request to router.php (for dynamic routes)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ router.php [QSA,L]
# For all other cases (when files or directories DO exist)
# serve them as-is without rewriting (static files, existing directories)
RewriteRule ^(.*)$ - [QSA,L]
In production mode, Apache handles the routing:
| Aspect | Development (PHP Server) | Production (Apache + .htaccess) |
|---|---|---|
| Server Command | php -S localhost:8000 router.php | Apache virtual host |
| Static File Handling | PHP checks file existence, returns false | Apache serves directly via .htaccess |
| URL Routing | All requests to router.php | Only non-existing files to router.php |
| Performance | Good for development | Optimized for production |
| Configuration | Zero configuration | Requires mod_rewrite + .htaccess |
project-root/ ├── router.php # Main router logic (works in both environments) ├── index.php # Entry point for .htaccess (optional) ├── .htaccess # Apache rewrite rules ├── assets/ │ ├── style.css # Stylesheet │ ├── demo-image.svg # Demo image │ └── docs.php # This documentation └── README.md # Project documentation
Check that Apache has mod_rewrite enabled and AllowOverride All is set for your directory.
Verify .htaccess file permissions (644) and that it's in the correct directory (document root).
Check Apache error logs: tail -f /var/log/apache2/error.log
# Test development server php -S localhost:8000 router.php curl http://localhost:8000/hello # Test production (assuming files in /var/www/html/) curl http://localhost/hello
This dual compatibility pattern is useful for: