How to Automatically Generate SEO-Friendly URLs in PHP

Santaji GadeOn-Page SEOSEO2 weeks ago616 Views

SEO-friendly URLs

A URL like /post.php?id=4821 tells search engines nothing. Here's the complete PHP code to fix that automatically transliteration, uniqueness checks, server rewrite rules, and a live slug generator.

Technical SEO SEO-Friendly URLs PHP Slugs

A URL like /post.php?id=4821 tells a search engine and a user absolutely nothing. A URL like /blog/seo-friendly-urls-php tells them everything before the page even loads. Turning the first into the second is a single PHP function, and this guide gives you the complete, working code.

SEO-friendly URLs are automatically generated in PHP by converting a title or heading into a clean, lowercase, hyphen-separated slug, stripping special characters, transliterating accented letters, and checking the result against existing records to guarantee it stays unique.

We covered the writing side of this in our SEO-friendly blog posts guide. This article handles the technical half: the actual PHP that turns a title into a clean, working URL automatically.

Advertisement
Advertisement
3-5

words is the ideal slug length range for both readability and search performance

1

PHP function handles transliteration, cleanup, and formatting in a single pass

301

redirect status code required any time an already-indexed slug changes

What Turning a Title Into a Slug Actually Looks Like

10 Content Writing Mistakes That Reduce Rankings!
10-content-writing-mistakes-that-reduce-rankings

Step 1: The Core Slugify Function

This single function handles transliteration, lowercasing, and cleanup in one pass, using PHP's built-in iconv function.

<?php
function slugify(string $text, string $separator = '-'): string {
    // Transliterate accented and Unicode characters to plain ASCII
    $text = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $text);

    // Lowercase everything
    $text = strtolower($text);

    // Replace anything that isn't a letter or number with the separator
    $text = preg_replace('/[^a-z0-9]+/', $separator, $text);

    // Trim separators from both ends
    $text = trim($text, $separator);

    // Collapse repeated separators into a single one
    $text = preg_replace('/' . preg_quote($separator, '/') . '+/', $separator, $text);

    return $text;
}

echo slugify('10 Content Writing Mistakes That Reduce Rankings!');
// Output: 10-content-writing-mistakes-that-reduce-rankings

A complete, working slugify function using PHP's built-in iconv transliteration

Advertisement
Advertisement

Step 2: Guaranteeing Uniqueness Against a Database

Two posts titled the same thing will otherwise generate identical slugs. This version checks the database and appends a number if needed.

<?php
function generateUniqueSlug(PDO $pdo, string $title, ?int $excludeId = null): string {
    $baseSlug = slugify($title);
    $slug = $baseSlug;
    $counter = 2;

    while (slugExists($pdo, $slug, $excludeId)) {
        $slug = $baseSlug . '-' . $counter;
        $counter++;
    }
    return $slug;
}

function slugExists(PDO $pdo, string $slug, ?int $excludeId = null): bool {
    $sql = "SELECT COUNT(*) FROM posts WHERE slug = :slug";
    $params = ['slug' => $slug];

    if ($excludeId !== null) {
        $sql .= " AND id != :id";
        $params['id'] = $excludeId;
    }

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    return (int) $stmt->fetchColumn() > 0;
}

Appends -2, -3, and so on until an unused slug is found; excludeId prevents false positives when editing an existing post

Step 3: Putting It Together on Save

<?php
$title = $_POST['title'];
$slug = generateUniqueSlug($pdo, $title);

$stmt = $pdo->prepare("INSERT INTO posts (title, slug, created_at) VALUES (:title, :slug, NOW())");
$stmt->execute(['title' => $title, 'slug' => $slug]);

A complete insert flow: title comes in, a guaranteed-unique SEO-friendly URL goes into the database

Step 4: Making the URL Actually Work

Generating the slug is only half the job. The server needs to route that clean URL to the right script.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^blog/([a-z0-9-]+)/?$ blog-post.php?slug=$1 [L,QSA]
location /blog/ {
    rewrite ^/blog/([a-z0-9-]+)/?$ /blog-post.php?slug=$1 last;
}

Live Slug Generator

Type a title below to see the exact SEO-friendly URL the PHP function above would generate.

Live Slug Generator

Mirrors the slugify() function's logic in real time

10-content-writing-mistakes-that-reduce-rankings
3 words · 48 characters

Why SEO-Friendly URLs Matter Beyond Rankings

According to Achromatic's guide to SEO-friendly slugs, a clean URL improves click-through rate directly, since users can see what a page is about before ever clicking the search result.

SEO-friendly URLs also make internal linking easier to manage. A URL like /blog/seo-friendly-urls-php is self-documenting in code, on a sitemap, or in analytics reports, unlike an opaque numeric ID that requires a database lookup to understand.

Advertisement
Advertisement

Transliteration Options Beyond the Basic Function

According to Slug Generator's guide to creating SEO-friendly URL slugs in PHP, PHP's intl extension offers ICU-based transliteration for cases where iconv's simpler approach does not cover a specific language well enough.

According to Our Code World's guide to creating URL slugs properly in PHP, a custom character map is another option for teams needing precise control over how specific accented or Cyrillic characters convert, beyond what a generic transliteration function provides by default.

Testing Your SEO-Friendly URL Setup End to End

According to PHP's official preg_replace documentation, testing the slugify function against edge cases, titles with numbers, punctuation, and mixed languages, catches formatting issues before they reach production.

Once the PHP side generates a correct SEO-friendly URL, confirm the rewrite rule actually resolves it by visiting the new URL directly in a browser, not just linking to it internally.

According to Edureka's community discussion on generating SEO-friendly URL slugs, a working rewrite rule returns the correct page with a 200 status; a broken one returns a 404 even though the slug itself was generated correctly.

Common Mistakes to Avoid

MistakeWhy It Matters
Using auto-increment IDs as the slug/post/4821 means nothing to users or search engines
Changing a slug without a 301 redirectBreaks every existing backlink and indexed search result
Leaving slugs 8-10+ words long3-5 words performs best for both readability and search
Skipping transliteration entirelyAccented characters get silently stripped, mangling the slug
All-numeric slugsSome frameworks route pure numbers to ID-based logic unexpectedly

Handling Slug Changes Safely

According to DevToolHub's 2026 URL slug best practices guide, once a URL is indexed, has backlinks, or has been shared, changing the slug breaks every one of those existing references unless a redirect is put in place.

According to Rich Dev Tools' guide to URL slug rules and SEO impact, a simple redirects table mapping old slugs to new ones, checked before a 404 response, handles this cleanly without manual .htaccess edits for every single change.

Advertisement
Advertisement

FAQs on Generating SEO-Friendly URLs in PHP

Do I need a library to generate SEO-friendly URLs in PHP?
No. PHP's built-in iconv and preg_replace functions handle transliteration and cleanup without any external dependency, as shown in the slugify function above.
How do I handle two posts with the same title?
Check the generated slug against existing database records, and append a number like -2 or -3 if a match is found, as covered in Step 2 above.
What happens if I change a slug after the page is already indexed?
The old URL stops working unless you add a 301 redirect from the old slug to the new one. Skipping this breaks existing backlinks and search rankings tied to that URL.
How long should a generated slug be?
3 to 5 words performs best for SEO-friendly URLs. Google does not penalize longer URLs directly, but shorter, keyword-focused slugs tend to perform better in both search results and click-through rate.
Does this slugify function handle non-English characters?
Yes, for accented Latin characters like é, ñ, and ü, through iconv's transliteration. Non-Latin scripts like Chinese or Arabic require a more advanced transliteration library.
Should the slug include stop words like "the" or "and"?
Removing common stop words is optional but often recommended, since it shortens the slug and keeps focus on the actual keywords the page targets.

> what_we_learn_today.log

[OK]

iconv transliteration handles accented characters without any external library

[OK]

A database uniqueness check prevents duplicate slugs from colliding

[OK]

Generating the slug is only half the job; server rewrite rules make it live

[OK]

3-5 words is the sweet spot for slug length

[OK]

Never change an indexed slug without a 301 redirect in place

[OK]

Avoid auto-increment IDs and all-numeric slugs entirely

0 Votes: 0 Upvotes, 0 Downvotes (0 Points)

Leave a reply

Loading Next Post...
Search
Popular Now
Loading

Signing-in 3 seconds...

Signing-up 3 seconds...