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.
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,
);
(
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>
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>
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
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");
?>
$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");
?>
tnx its awesome
ReplyDeleteGood Post Sri..
ReplyDeleteCan 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
[email protected]
Great article infact but when we put _ in title it shows error.So better throw _also.
ReplyDeleteVery nice
The code don't work with special characters like ç Ç é à ó and !@#$%¨&*().
ReplyDeleteIf have some this characters break the code.
good article but php is very slow and not good for big web application..
ReplyDeletethanks
ReplyDeleteGreat job! Everything is working properly, there is only superfluous comma - in table creation at the end of "url TEXT" :)
ReplyDeleteGreat article :) I appreciate your work.
ReplyDeleteBelow link is basic rewrite condition.
http://phpcreating.blogspot.com/2010/02/url-rewriting.html
Thanks
Bhargav Anadkat
Great you helped me allot
ReplyDeleteThanks
wow it's cool...
ReplyDeletealthough I do not know about PHP
good good
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.
ReplyDeleteWhat about the Polish letters ?
ReplyDeleteWhat about the Polish letters eg. ąęśćłżźó
ReplyDeleteI can not see the point to do this with php.
ReplyDelete@mercs
ReplyDeleteUnicode support add this tag on header
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
//good article but php is very slow and not good for big web application..//
ReplyDeleteFacebook is a total php site.
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
ReplyDeletenice...good job...i will use in my site
ReplyDeleteHey,nice tutorial
ReplyDeleteCool man
ReplyDeleteits good
ReplyDeleteNice..
ReplyDeleteHow-to publish jquery with this?
Thx
@Srinivas Tamada
ReplyDeleteYou 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.
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.
ReplyDeleteExample: test-1.html, test-2.html, etc...
Yes title, url should be UNIQUE -> Updated
ReplyDeleteHello, 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.
ReplyDeleteHello Srinivas...
ReplyDeletecan you give me example insert url like test-1.html, test-2.html, etc... if title same? thanks before...
Hi great post, It's easy to create friendly urls with php and mysql. Keep up the good work!
ReplyDeleteGreat article Srinivas!
ReplyDeletenice...good job...i will use in my site
ReplyDeletehey, but turkish shows corrupted characters...
ReplyDelete@ good article but php is very slow and not good for big web application..
ReplyDeletehow 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
For .htaccess you could do this:
ReplyDeleteRewriteEngine 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
@Amini
ReplyDeleteThank you :) it's useful
I dont understand where I m wrong..
ReplyDeleteı m always taking "Not URL Available 404." error.. :(
I did everything , but results not so good.. , Srivinas please help me.Thank you,
404 Error please check .htaccess code
ReplyDeletea masterpiece...
ReplyDeletecan we use unicode in URL like this(2011/05/20/शुल्कवृद्धि-रोक्न) ?? I tried it but didn't work. Can we fix it??
ReplyDeleteSrini, 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.
ReplyDeleteAlso on this topic of .htaccess the following link is also very exhaustive and helpful.
http://corz.org/serv/tricks/htaccess2.php
Wowwwww... Srinivas Great Article!!!
ReplyDeleteI 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!!
@Reyvolsam
ReplyDeleteThank you :)
How should db.php look like?
ReplyDeleteboss, 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.
ReplyDeletenice post :)
ReplyDeletemind blowing Dude: Thanks
ReplyDeleteRelated part:
ReplyDelete.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...
yes, redirect is not at all working...
Deletehi i m yogesh
ReplyDeleteits 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 ??
Srinivas Great Article but it is not working with Arabic Characters :(
ReplyDeleteCan you please make a separate article for Unicode Characters in URLs?
Thanks
who does this code mean?
ReplyDeleteRewriteRule ^([a-zA-Z0-9-/]+).html$ article.php?url=$1
This code is very useful but i want to something like this.
ReplyDeletehttp://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
=( the htaccess doesnt work ! i use Amini htaccess =) Thx =) excelent example... =)
ReplyDeletehow to change url http://www.findtoget.com/review.php?getid=o-H1yn1o&creed-one-last-breath.mp4.html
ReplyDeleteto
http://www.findtoget.com/review/getid/o-H1yn1o/creed-one-last-breath.mp4.html
sendme file .htaccess for that
[email protected]
Hello Sir, am unable to redirect the page can you please provide me .htaccess mod_rewrite.so code Please help me in this. Thanks
ReplyDeleteI'm not that satisfied..
ReplyDeleteTry "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...
this is a horrible approach with horrible code organization. Very bad.
ReplyDeletevery 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
ReplyDeleteThank you for this :D Im new to SEO so this helpful for a start
ReplyDeletethis is my link for website.Not in wordpress
ReplyDeletehttp://testifyforisrael.com/index.php?page=page&id=19
i want like this http://testifyforisrael.com/index.php/our-mission
rply me asap.
Thanks for this great information. Its really truly quality information.
ReplyDeleteGreat post, useful information. I used to use Underscores myself haha, but the dashes look a lot cleaner if i do say so myself.
ReplyDeleteHi Sir,
ReplyDeletei 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
I test your script in my local server. but, it doesn't work, i opened mod_rewrite in httpd.conf. pls, alittle help me.
ReplyDeleteHi Admin,
ReplyDeleteGood 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
The authoritative nature of URLs has decreased with time but it still doesn't hurt to have a keyword rich URL.
ReplyDeleteThank you!
ReplyDeletewhere is the db.php??
ReplyDeleteis require a db.php
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.
ReplyDeleteyour post is very usefull and helpfull .
ReplyDeletenice info,, but
ReplyDeletehowto with replace (/,&.) with (-)?
thanks
thanks for sharing this information..
ReplyDeleteRewriteEngine On
ReplyDeleteRewriteRule ^([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 [email protected]
Hey i have many links...
ReplyDelete1: 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
by applying your tutorial,
ReplyDeleteurl 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.
Great article.
ReplyDeleteFinally I can understand SEO work.
this simple explanation indeed.
great work srinivas.
Great article Siriniwas....
ReplyDeleteKeep posting, thanks for share.
ReplyDeletehow can i convert
ReplyDeletelogin.php
to
login.html
with.htaccess
any one know that.
Hi,
ReplyDeleteI did all the changes properly but it is redirecting to my main site. It's not working please help me.
Thanks its working.
ReplyDeleteThis is simple and use full article.
Thanks Srinivas.
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
ReplyDelete"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...
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.
ReplyDeletehow do it. in nginx server? nginx server cant read .htaccess. please help me. urgent. thanks before
ReplyDeleteAfter 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.
ReplyDeleteIt is indeed a nice one.
VERY COOOOOOOOOOOOOOOOL
ReplyDeleteI LOVE YOU 9LESSON TEAM
CHEEEEEEEEEERS
LOVE THIS TUROIAL>
VERY GOOOOOOOOOOOOOOOOOOD
HONESTLY VERY HAPYYY TO FOUND THIS TUTORIAL
PLEASE CARRY ON
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
ReplyDelete.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
Hi ! Very good tutorial - but i still problem with unicode in this part
ReplyDelete$urltitle=preg_replace('/[^a-z0-9]/i',' ', $newtitle);
how can i use russian characters for link name ?
Thanx in advance !
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 .
ReplyDeletewhat is the code for db.php
ReplyDeletewhat is the code for db.php
ReplyDelete@Kanchan Kalia Updated db.php
ReplyDeletei 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
ReplyDeletethanx it is working.
ReplyDeleteVery good job
ReplyDeleteNotice: Undefined variable: blogurl in E:\xamp\htdocs\seo\publish.php on line 69 i am getting error..pls help me.
ReplyDeleteWill probably use this on my own site, i´ve noticed that friendly URLs is extremly important...
ReplyDeleteThank you so much for wonderful post. It was really saves my time lot.
ReplyDeleteThanks for your code..
ReplyDeleteby applying your tutorial,
ReplyDeleteurl 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.
by applying your tutorial,
ReplyDeleteurl 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.
same problem
DeleteApply .htaccess
DeleteRewriteEngine On
RewriteRule ^([a-zA-Z0-9-/]+).html$ article.php?url=$1
RewriteRule ^([a-zA-Z0-9-/]+).html/$ article.php?url=$1
Not Working for the 2 links try for other link with url type
Deleteie: article.php?url=12
profile.php?p_url=20
try this, will not work for this please solve this one..
why i use all language supported...please help...sir
ReplyDeleteI really love this blog... :)
ReplyDeleteThis comment has been removed by the author.
ReplyDeletein my case for one page it is working properly.i:e(profile.php?view=anup);
ReplyDeleteBut if there are two different files and different functions like:
(1) profile.php?view=anup --------------> This is one file.
In this case i can n't be able to use the .htaccess the forst function is working
(2) state.php?statename=odisha ---------> The Other One.
If i write like this in .htaccess file
RewriteRule ^([a-zA-Z0-9-/]+).html$ profile.php?view=$1
RewriteRule ^([a-zA-Z0-9-/]+).html$ state.php?statename=$1
Yes Yes I got it...
ReplyDeleteRewriteRule ^([a-zA-Z0-9_-]+)$ state.php?state_name=$1
ReplyDeleteRewriteRule ^([a-zA-Z0-9_-]+)/$ state.php?state_name=$1
RewriteRule ^([a-zA-Z0-9_-]+)$ profile.php?user_id=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ profile.php?user_id=$1
state.php?state_name=odisha
profile.php?user_id=07
For Single Link its working fine but in this case .htaccess is not working infact showing some error...
can anyone suggest me here, its necessary.. please reply ASAP.....
thanks you.....
ReplyDeleteGood one Srinivas.
ReplyDelete