SEO-friendly URLs improve readability and indexing by search engines. Let’s see how to create clean and optimized URLs using PHP and .htaccess.
1. What is an SEO-Friendly URL?
A typical dynamic URL:
https://www.site.com/page.php?id=15&category=tech
Optimized SEO-friendly version:
https://www.site.com/tech/web-development
This structure improves user experience and helps search engines index pages more efficiently.
2. URL Rewriting with .htaccess
To create SEO-friendly URLs, enable Apache’s mod_rewrite and add the following rules to your .htaccess
file:
RewriteEngine On
RewriteBase /
RewriteRule ^blog/([a-zA-Z0-9_-]+)/?$ blog.php?post=$1 [L,QSA]
RewriteRule ^category/([a-zA-Z0-9_-]+)/?$ category.php?name=$1 [L,QSA]
Important: Ensure mod_rewrite is enabled in your Apache server.
3. Handling SEO-Friendly URLs in PHP
Extract URL parameters using PHP:
if (isset($_GET['post'])) {
$postSlug = htmlspecialchars($_GET['post']);
echo "Currently viewing blog post: " . $postSlug;
}
To generate SEO-friendly slugs for database storage:
function seoFriendlyUrl($string) {
$string = strtolower($string);
$string = preg_replace("/[ğüşıöç]/u", "gusioc", $string);
$string = preg_replace("/[^a-z0-9]+/", "-", $string);
return trim($string, "-");
}
echo seoFriendlyUrl("PHP SEO Friendly URLs");
Output: php-seo-friendly-urls
In Summary;
- Use Short and Descriptive URLs → Prefer
/tech/php
over/tech/php-tutorial
. - Include Keywords → Use relevant keywords in URLs.
- Avoid Unnecessary Parameters → Avoid cluttered structures like
?id=123
. - Use Lowercase Letters →
/php-tutorial
is preferred over/PHP-Tutorial
. - Remove Spaces and Special Characters → Use
-
or_
instead of spaces.
Post Comment