How to do URL re-writing in PHP?
Mastering Clean URLs: A Developer's Guide to URL Rewriting in PHP Implementing clean URLs—where readable, human-friendly paths are used instead of messy query...
Mastering Clean URLs: A Developer's Guide to URL Rewriting in PHP
Implementing clean URLs—where readable, human-friendly paths are used instead of messy query strings or deep directory structures—is crucial for both user experience and Search Engine Optimization (SEO). When building dynamic applications in PHP, mastering URL rewriting is a fundamental skill. This guide will walk you through the practical steps for achieving this transformation, addressing your specific requirements for handling content slugs and IDs.
The Philosophy of Clean URLs
The core goal of URL rewriting is to map a friendly URL structure (e.g., /videos/play/google-io-2009-wave-intro) into an internal, structured request that the PHP application can easily process. This process moves the complexity away from the browser and into the server or application logic.
We are essentially transforming:
http://example.com/videos/play/slug $\rightarrow$ index.php?category=videos&type=play&title=slug
This transformation allows us to use parameters (like title or id) for data retrieval, which is cleaner and more manageable than relying on complex path structures.
Method 1: Server-Level Rewriting using .htaccess
The most efficient way to handle large volumes of URL rewriting before the request even hits your PHP scripts is by using server configuration files, specifically Apache's .htaccess file (using mod_rewrite). This keeps your application logic cleaner.
In your root directory (or the specific subdirectory where you want this rule applied), create or edit the .htaccess file:
RewriteEngine On
RewriteBase /
# Rule to handle the desired structure for video playback
RewriteRule ^videos/play/(.*)$ play.php?title=$1 [L,QSA]
Explanation:
* RewriteEngine On: Activates the rewrite engine.
* RewriteRule ...: Defines the rule. It looks for URLs matching the pattern.
* ^videos/play/(.*)$: This captures everything after /videos/play/ into the variable $1 (this becomes your slug or ID).
* play.php?title=$1: This rewrites the URL internally to a clean PHP file, appending the captured value as a query parameter (title).
This method effectively handles your first requirement: converting /videos/play/google-io-2009-wave-intro into play.php?title=google-io-2009-wave-intro.
Method 2: Application-Level Handling in PHP
While .htaccess handles the routing, the PHP script must handle the data retrieval. Once the request hits play.php, your PHP code needs to read the parameters and query the database.
Here is how you would process the incoming request within that file:
<?php
// Assuming this script is play.php
if (isset($_GET['title'])) {
$videoTitle = $_GET['title'];
// Step 2: Use $videoTitle to query your MySQL database
// Example: $stmt = $pdo->prepare("SELECT * FROM videos WHERE title = ?");
echo "Displaying video for title: " . htmlspecialchars($videoTitle);
} elseif (isset($_GET['id'])) {
$videoId = $_GET['id'];
// Example: $stmt = $pdo->prepare("SELECT * FROM videos WHERE id = ?");
echo "Displaying video with ID: " . htmlspecialchars($videoId);
} else {
echo "Error: Missing video identifier.";
}
?>
This application-level logic allows you to handle both cases seamlessly, depending on which parameter (title or id) was passed by the URL.
SEO and Best Practices: Slug vs. ID
You asked which structure is best for SEO and management:
/videos/play/google-io-2009-wave-intro(Slug-based): Recommended. Slugs are highly readable, descriptive, and excellent for SEO. They tell search engines exactly what the page is about./videos/play/203/google-io-2009-wave-intro(ID-based Path): Less readable for users and less beneficial for SEO unless the ID itself is meaningful content (which it usually isn't).
For modern web applications, prioritizing human readability (slugs) over purely numeric paths generally yields better engagement and SEO results. Frameworks like Laravel, which heavily emphasize routing and clean URLs, make this separation of concerns extremely straightforward, providing robust tools for managing these transitions efficiently.
Conclusion
Implementing URL rewriting is a layered process involving both server configuration and application logic. Start with .htaccess to handle the initial mapping, and then use your PHP code to safely extract and utilize the data passed via query parameters. By focusing on clean, descriptive slugs, you ensure a better experience for your users and improved visibility in search engine results.
Stefan
SEO engineer and Laravel developer. Building tools to help Laravel applications rank higher in search results.