SEO Friendly URLs with PHP
Wall Script
Follow Me:
Wednesday, April 06, 2011

SEO Friendly URLs with PHP

This post explains how to create SEO friendly URL with dynamic content using PHP and .htaccess mod redirection. Friendly URLs improves your site search engines ranking. Before trying this you have to enable mod_rewrite.so module at httpd.conf. It’s simple just few lines of PHP code converting title data to clean URL format.

SEO Friendly URLs with PHP

Download Script     Live Demo

Database
Sample database blog table columns id, title, body and url.
CREATE TABLE blog
(
id INT PRIMARY KEY AUTO_INCREMENT,
title TEXT UNIQUE,
body TEXT,
url TEXT UNIQUE,
);

Publish.php
Contains PHP code. Converting title text to friendly url formate and storing into blog table.
<?php
include('db.php');
function string_limit_words($string, $word_limit)
{
$words = explode(' ', $string);
return implode(' ', array_slice($words, 0, $word_limit));
}

if($_SERVER["REQUEST_METHOD"] == "POST")
{
$title=mysql_real_escape_string($_POST['title']);
$body=mysql_real_escape_string($_POST['body']);
$title=htmlentities($title);
$body=htmlentities($body);
$date=date("Y/m/d");
//Title to friendly URL conversion
$newtitle=string_limit_words($title, 6); // First 6 words
$urltitle=preg_replace('/[^a-z0-9]/i',' ', $newtitle);
$newurltitle=str_replace(" ","-",$newtitle);
$url=$date.'/'.$newurltitle.'.html'; // Final URL
//Inserting values into my_blog table
mysql_query("insert into blog(title,body,url) values('$title','$body','$url')");
}
?>
//HTML Part
<form method="post" action="">
Title:
<input type="text" name="title"/>
Body:
<textarea name="body"></textarea>
<input type="submit" value=" Publish "/>
</form>

Article.php
Contains HTML and PHP code. Displaying content from blog table.
<?php
include('db.php');
if($_GET['url'])
{
$url=mysql_real_escape_string($_GET['url']);
$url=$url.'.html'; //Friendly URL 
$sql=mysql_query("select title,body from blog where url='$url'");
$count=mysql_num_rows($sql);
$row=mysql_fetch_array($sql);
$title=$row['title'];
$body=$row['body'];
}
else
{
echo '404 Page.';
}
?>
//HTML Part
<body>
<?php
if($count)
{
echo "<h1>$title</h1><div class='body'>$body</div>";
}
else
{
echo "<h1>404 Page.</h1>";
}
?>
</body>

.htaccess
URL rewriting file. Redirecting original URL 9lessons.info/article.php?url=test.html to 9lessons.info/test.html
RewriteEngine On

RewriteRule ^([a-zA-Z0-9-/]+).html$ article.php?url=$1
RewriteRule ^([a-zA-Z0-9-/]+).html/$ article.php?url=$1

db.php
Database configuration file, just modify database credentials.
<?php
$mysql_hostname = "localhost";
$mysql_user = "username";
$mysql_password = "password";
$mysql_database = "database";
$prefix = "";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
?>
Was this article helpful?
Thanks! Your feedback helps us to improve 9lessons.info


103 comments:

  1. tnx its awesome

    ReplyDelete
  2. Good Post Sri..

    Can u help me pls..

    I can not see any changes in my site, is there any problum in .htaccess and can u sent me a .htaccess fil..

    Thanks,
    Vishal
    vishalgupta.rgec@gmail.com

    ReplyDelete
  3. Great article infact but when we put _ in title it shows error.So better throw _also.

    Very nice

    ReplyDelete
  4. The code don't work with special characters like ç Ç é í ó and !@#$%¨&*().

    If have some this characters break the code.

    ReplyDelete
  5. good article but php is very slow and not good for big web application..

    ReplyDelete
  6. Great job! Everything is working properly, there is only superfluous comma - in table creation at the end of "url TEXT" :)

    ReplyDelete
  7. Great article :) I appreciate your work.

    Below link is basic rewrite condition.
    http://phpcreating.blogspot.com/2010/02/url-rewriting.html

    Thanks
    Bhargav Anadkat

    ReplyDelete
  8. Great you helped me allot

    Thanks

    ReplyDelete
  9. wow it's cool...
    although I do not know about PHP
    good good

    ReplyDelete
  10. i think the problem for this code is the friendly url save to the database, there will be a scenario that the title needs to be change, it would be better that your friendly url is created on the fly and not to be database.

    ReplyDelete
  11. What about the Polish letters ?

    ReplyDelete
  12. What about the Polish letters eg. ąęśćłżźó

    ReplyDelete
  13. I can not see the point to do this with php.

    ReplyDelete
  14. @mercs

    Unicode support add this tag on header

    <meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />

    ReplyDelete
  15. //good article but php is very slow and not good for big web application..//

    Facebook is a total php site.

    ReplyDelete
  16. php,asp,ruby or any.. Doesnt matter, php is not slow, it depends on how you create your structure. And how you optimize your query

    ReplyDelete
  17. nice...good job...i will use in my site

    ReplyDelete
  18. Hey,nice tutorial

    ReplyDelete
  19. Nice..
    How-to publish jquery with this?
    Thx

    ReplyDelete
  20. @Srinivas Tamada

    You don't need the http-equiv attributes. Browser's ignore them so all you need is charset.

    <meta charset=utf-8>

    As well to fix a bug in IE to stop code injection it needs to be in the first 150kb of the header so put it above <title> just after the <head> tag.

    ReplyDelete
  21. The URL should be unique. Id you have 2 post with the title 'Test', it'll show the first 'Test' post only. I suggest combining post ID and the post title together to create a unique URL.

    Example: test-1.html, test-2.html, etc...

    ReplyDelete
  22. Yes title, url should be UNIQUE -> Updated

    ReplyDelete
  23. Hello, I was just wondering if you can do a tutorial, about facebook like notification system? It would be really nice :D. Your blog it's great.

    ReplyDelete
  24. Hello Srinivas...
    can you give me example insert url like test-1.html, test-2.html, etc... if title same? thanks before...

    ReplyDelete
  25. Hi great post, It's easy to create friendly urls with php and mysql. Keep up the good work!

    ReplyDelete
  26. nice...good job...i will use in my site

    ReplyDelete
  27. hey, but turkish shows corrupted characters...

    ReplyDelete
  28. @ good article but php is very slow and not good for big web application..

    how about Facebook, is it big enough?

    @ I can not see the point to do this with php.

    This could give you a good ranking for your PHP website on Google Search results

    ReplyDelete
  29. For .htaccess you could do this:

    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ article.php?url=$1 [PT,L]

    What this will do is first check if the request IS NOT an actual file and folder, then it is passed on to article.php.

    With article.php, you check if the request exists in the database, if not then display a Page Not Found message

    ReplyDelete
  30. I dont understand where I m wrong..
    ı m always taking "Not URL Available 404." error.. :(
    I did everything , but results not so good.. , Srivinas please help me.Thank you,

    ReplyDelete
  31. 404 Error please check .htaccess code

    ReplyDelete
  32. can we use unicode in URL like this(2011/05/20/शुल्कवृद्धि-रोक्न) ?? I tried it but didn't work. Can we fix it??

    ReplyDelete
  33. Srini, I am a regular lurker at your site but do not post much. I really like your articles since they are very well written and, most importantly, love the baby steps.

    Also on this topic of .htaccess the following link is also very exhaustive and helpful.

    http://corz.org/serv/tricks/htaccess2.php

    ReplyDelete
  34. Wowwwww... Srinivas Great Article!!!

    I speak spanish, but i can understad a few english, and thank for this article, it´s difficult to find an article like this in spanish!

    Gracias y Saludos desde Mexico!!

    ReplyDelete
  35. How should db.php look like?

    ReplyDelete
  36. boss, thanks a lot for this article. its really helpful for me. A lot of time i search for apache url rewrite on search engine but i cant find one like this. this is great.

    ReplyDelete
  37. Related part:
    .htaccess
    URL rewriting file. Redirecting original URL 9lessons.info/article.php?url=test.html to 9lessons.info/test.html

    You say "redirecting"... But it is not redirecting. It is only the standard way to make seo friendly urls. NOT for redirecting old dynamic urls to sef ones...

    ReplyDelete
  38. hi i m yogesh
    its give some error
    (The server encountered an internal error or misconfiguration and was unable to complete your request.

    Please contact the server administrator, webmaster@localhost and inform them of the time the error occurred, and anything you might have done that may have caused the error.

    More information about this error may be available in the server error log.)

    now wat to do ??

    ReplyDelete
  39. Srinivas Great Article but it is not working with Arabic Characters :(

    Can you please make a separate article for Unicode Characters in URLs?

    Thanks

    ReplyDelete
  40. who does this code mean?

    RewriteRule ^([a-zA-Z0-9-/]+).html$ article.php?url=$1

    ReplyDelete
  41. This code is very useful but i want to something like this.
    http://codedunia.in/c-language/introduction-to-c-language/
    I do this task but when anyone type:
    http://codedunia.in/c-language/introduction-to-c-language.php then it also redirect to:
    http://codedunia.in/c-language/introduction-to-c-language/
    Please give me the solution either here or to my facebook msg http://facebook.com/yogidreamss

    ReplyDelete
  42. =( the htaccess doesnt work ! i use Amini htaccess =) Thx =) excelent example... =)

    ReplyDelete
  43. how to change url http://www.findtoget.com/review.php?getid=o-H1yn1o&creed-one-last-breath.mp4.html

    to
    http://www.findtoget.com/review/getid/o-H1yn1o/creed-one-last-breath.mp4.html

    sendme file .htaccess for that

    findtoget.com@gmail.com

    ReplyDelete
  44. Hello Sir, am unable to redirect the page can you please provide me .htaccess mod_rewrite.so code Please help me in this. Thanks

    ReplyDelete
  45. I'm not that satisfied..

    Try "This $ is a test"
    and you will get "This-$-is---.html" in your live example.

    or with "¶ ÄöÜ" you'll get "¶-Ã�öÃ�.html"

    -not very se friendly url's...

    ReplyDelete
  46. this is a horrible approach with horrible code organization. Very bad.

    ReplyDelete
  47. very interesting post. if you want to read a post similar to this go to http://our-knowledge-base.blogspot.com/2012/04/making-clean-string-for-seo-friendly.html

    ReplyDelete
  48. Thank you for this :D Im new to SEO so this helpful for a start

    ReplyDelete
  49. this is my link for website.Not in wordpress
    http://testifyforisrael.com/index.php?page=page&id=19

    i want like this http://testifyforisrael.com/index.php/our-mission

    rply me asap.

    ReplyDelete
  50. Thanks for this great information. Its really truly quality information.

    ReplyDelete
  51. Great post, useful information. I used to use Underscores myself haha, but the dashes look a lot cleaner if i do say so myself.

    ReplyDelete
  52. Hi Sir,
    i am working on your friendly url articles but i am facing problem. i have 2 pages mobile_phones.php and mobile_features.php

    RewriteEngine On

    RewriteRule ^([a-zA-Z0-9-/]+).html$ mobile_phones.php?url=$1
    RewriteRule ^([a-zA-Z0-9-/]+).html/$ mobile_phones.php?url=$1

    RewriteRule ^([a-zA-Z0-9-/]+).html$ mobile_features.php?url=$1
    RewriteRule ^([a-zA-Z0-9-/]+).html/$ mobile_features.php?url=$1

    and just upper two lines are working , i mean when we click on category they get mobiles and show on mobile_phones.php and when i click on mobile features it do not redirect to mobile_features.php it again redirect to mobile_phones.php i am very confused kindly help me in this matter i will appreciate.

    Thank You So Much

    ReplyDelete
  53. I test your script in my local server. but, it doesn't work, i opened mod_rewrite in httpd.conf. pls, alittle help me.

    ReplyDelete
  54. Hi Admin,

    Good work for this code, but i faced some problem in .htaccess file..


    RewriteEngine On

    RewriteRule ^([a-zA-Z0-9-/]+).html$ test1.php?url=$1
    RewriteRule ^([a-zA-Z0-9-/]+).html/$ test1.php?url=$1

    RewriteRule ^([a-zA-Z0-9-/]+).html$ test2.php?url=$1
    RewriteRule ^([a-zA-Z0-9-/]+).html/$ test2.php?url=$1

    First two lines its working fine, second line of
    RewriteRule ^([a-zA-Z0-9-/]+).html$ test2.php?url=$1
    RewriteRule ^([a-zA-Z0-9-/]+).html/$ test2.php?url=$1

    Not working how to give multiple page within .htaccess fils. Can you please let me know Admin.

    Thanks

    ReplyDelete
  55. The authoritative nature of URLs has decreased with time but it still doesn't hurt to have a keyword rich URL.

    ReplyDelete
  56. where is the db.php??
    is require a db.php

    ReplyDelete
  57. Valuable information and excellent post you got here! I would like to thank you for sharing your thoughts and time into the stuff you post.Very informative tips.

    ReplyDelete
  58. your post is very usefull and helpfull .

    ReplyDelete
  59. nice info,, but
    howto with replace (/,&.) with (-)?
    thanks

    ReplyDelete
  60. thanks for sharing this information..

    ReplyDelete
  61. RewriteEngine On

    RewriteRule ^([a-zA-Z0-9-/]+).html$ article.php?url=$1
    RewriteRule ^([a-zA-Z0-9-/]+).html/$ article.php?url=$1

    what is the setting in php.ini
    plz Rep-sajid959@gmail.com

    ReplyDelete
  62. Hey i have many links...

    1: http://mysite.com/?nav=display&file=15
    2: http://mysite.com/?nav=profile&id=1
    etc,,,

    how to do:
    1: http://mysite.com/files/filename
    2: http://mysite.com/username


    Advance thanks

    ReplyDelete
  63. by applying your tutorial,
    url is generating like this :
    http://localhost/clean_url/article.php?url=2013/02/03/facebook.html
    but i want url look like this :
    http://localhost/clean_url/2013/02/03/facebook.html

    so how can i do that.

    ReplyDelete
  64. Great article.
    Finally I can understand SEO work.
    this simple explanation indeed.
    great work srinivas.

    ReplyDelete
  65. how can i convert

    login.php

    to

    login.html

    with.htaccess

    any one know that.

    ReplyDelete
  66. Hi,

    I did all the changes properly but it is redirecting to my main site. It's not working please help me.

    ReplyDelete
  67. Thanks its working.
    This is simple and use full article.

    Thanks Srinivas.

    ReplyDelete
  68. Nice one, and can you give full details, or a breif tutorial about ".htaccess" because, you've given one format, but i think still there are many formats, like
    "st.com/article.php?id=201&title=MyPage" to
    "st.com/article/My-Page"
    etc...
    I am seriously in need of this kind of links...

    ReplyDelete
  69. Pretty component of content. I simply stumbled upon your blog and in accession capital to claim that I get in fact loved account your weblog posts. Any way I’ll be subscribing to your feeds and even I fulfillment you get right of entry to consistently fast.

    ReplyDelete
  70. how do it. in nginx server? nginx server cant read .htaccess. please help me. urgent. thanks before

    ReplyDelete
  71. After a long search i came across your post. Your post has really worked me through the process of converting dynamic url to seo friendly url for my website.
    It is indeed a nice one.

    ReplyDelete
  72. VERY COOOOOOOOOOOOOOOOL
    I LOVE YOU 9LESSON TEAM
    CHEEEEEEEEEERS
    LOVE THIS TUROIAL>

    VERY GOOOOOOOOOOOOOOOOOOD
    HONESTLY VERY HAPYYY TO FOUND THIS TUTORIAL
    PLEASE CARRY ON

    ReplyDelete
  73. Dear 9 Lesson Team + Srivina, u dnt know, how much i m getting pleasure to found this tutorial is very excellent an dbest for me. i spend 4 to5 days to learn .htaccess but not got result to apply. by chance i got your this tutorial link on google
    .htaccess tutorial with demo. i have no any word to say Thanks, but i will just say. 9Lesson is very excellent an dgoood on internet

    Cheeeers

    ReplyDelete
  74. Hi ! Very good tutorial - but i still problem with unicode in this part
    $urltitle=preg_replace('/[^a-z0-9]/i',' ', $newtitle);
    how can i use russian characters for link name ?

    Thanx in advance !

    ReplyDelete
  75. hi i have seen u r tutorial it is very helpful for me,but in u r tutorial it is working for only page ,i need to working for multiple seo friendly urls .

    ReplyDelete
  76. i m first going to publish page and in insert the title and body then i have write those nto url then it give me page 404 . error

    ReplyDelete
  77. Notice: Undefined variable: blogurl in E:\xamp\htdocs\seo\publish.php on line 69 i am getting error..pls help me.

    ReplyDelete
  78. Will probably use this on my own site, i´ve noticed that friendly URLs is extremly important...

    ReplyDelete
  79. Thank you so much for wonderful post. It was really saves my time lot.

    ReplyDelete
  80. Thanks for your code..

    ReplyDelete
  81. by applying your tutorial,
    url is generating like this :
    http://localhost/nwr/article.php?url=2015/08/25/linkchange.html
    but i want url look like this :

    http://localhost/nwr/2015/08/25/linkchange.html

    so how can i do that.

    ReplyDelete
  82. by applying your tutorial,
    url is generating like this :
    http://localhost/nwr/article.php?url=2015/08/25/linkchange.html
    but i want url look like this :

    http://localhost/nwr/2015/08/25/linkchange.html

    so how can i do that.

    ReplyDelete
    Replies
    1. Apply .htaccess

      RewriteEngine On

      RewriteRule ^([a-zA-Z0-9-/]+).html$ article.php?url=$1
      RewriteRule ^([a-zA-Z0-9-/]+).html/$ article.php?url=$1

      Delete
  83. why i use all language supported...please help...sir

    ReplyDelete

Make in India