Jump to content

URL rewriting replace %20 signs with - to make seo friendly url


mlukac89

Recommended Posts

Hi, i never worked with .htaccess files because i didn't use it for anything, now i need one and i'm stuck into this.

 

I made a rule to remove .php extension from file and to make a url like this "localhost/blog/My%20first%20post"

 

Now i need to replace that white spaces and make a url to look like this "localhost/blog/My-first-post"

 

Here is my .htaccess file

RewriteEngine On

# Removes .php extension from inner_blog.php
RewriteRule ^blog/?$ blog.php [NC]

# Remove inner_blog.php and changing it to blog/articlename
RewriteRule ^blog/([^/]*)$ /inner_blog.php?title=$1 [L]
Link to comment
Share on other sites

I forgot my php code if it's important and if i need to change something

<?php

// mysql connection
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'mydatabase';

$dbh = new PDO('mysql:host='.$db_host.';dbname='.$db_name.';charset=utf8', $db_user, $db_pass);

if (isset($_GET['title']) && !empty($_GET['title']))
{
	$title = strip_tags($_GET['title']);

	$stmt = $dbh->prepare("SELECT * FROM blog WHERE heading = :title");
	$stmt->bindParam(':title', $title);
	$stmt->execute();

	$data = $stmt->fetch();


?>

<h1><?php echo htmlspecialchars($data['heading']); ?></h1>

<p><?php echo htmlspecialchars($data['text']); ?></p>

<?php } // else post blank page ?>
Link to comment
Share on other sites

Usually to avoid this type of problem, people proactively create slugs/permalinks for their entries.  It gets around the first issue you are facing, but also gets around the issue of insuring that there aren't multiple posts with the same title.  If that were to happen, you have to realize that one of the posts would essentially be orphaned because you would not have a way of getting to it through the system.  Sometimes people will just append a number at the beginning or end of the slug that insures it will be unique.  An easy way to do it is to prepend the internal ID number for the item.

 

Our forum software is an example:  https://forums.phpfreaks.com/topic/303631-url-rewriting-replace-%20-signs-with-to-make-seo-friendly-url/

 

 

As you can see, it has the advantage of correctly handling a situation where the actual title (as in your case) actually includes reference to a url parameter.  Any rule would be confused by that, if you just blindly url decode or do a search/replace looking for url encoded spaces.

 

Or another way to do it is to use a seperate ID parameter. This is what Stackoverflow does, for example:  http://stackoverflow.com/questions/43242311/custom-unmarshalling-for-xsdunion-when-genereting-classes-using-jaxb

 

My advice is to use one of these schemes which are tried and true, and at that point, your rewrite is simpler and more robust because you are controlling your url's rather than trying to deal with all the things people could put into a title and having to deal with the using spaces, url parameter characters or even dashes, which would become an issue.  You are retrieving articles by the slug/permalink rather than the title.  There are very few drawbacks other than what to do if people want to edit the title of an existing article.  In many cases it is best not to change the slugline after article creation, within a small window in case your site has been crawled by a search engine.  You don't want to risk losing a search engine placement with an editted post, because you found a small typo and fixed it.

Link to comment
Share on other sites

Usually to avoid this type of problem, people proactively create slugs/permalinks for their entries.  It gets around the first issue you are facing, but also gets around the issue of insuring that there aren't multiple posts with the same title.  If that were to happen, you have to realize that one of the posts would essentially be orphaned because you would not have a way of getting to it through the system.  Sometimes people will just append a number at the beginning or end of the slug that insures it will be unique.  An easy way to do it is to prepend the internal ID number for the item.

 

Our forum software is an example:  https://forums.phpfreaks.com/topic/303631-url-rewriting-replace-%20-signs-with-to-make-seo-friendly-url/

 

 

As you can see, it has the advantage of correctly handling a situation where the actual title (as in your case) actually includes reference to a url parameter.  Any rule would be confused by that, if you just blindly url decode or do a search/replace looking for url encoded spaces.

 

Or another way to do it is to use a seperate ID parameter. This is what Stackoverflow does, for example:  http://stackoverflow.com/questions/43242311/custom-unmarshalling-for-xsdunion-when-genereting-classes-using-jaxb

 

My advice is to use one of these schemes which are tried and true, and at that point, your rewrite is simpler and more robust because you are controlling your url's rather than trying to deal with all the things people could put into a title and having to deal with the using spaces, url parameter characters or even dashes, which would become an issue.  You are retrieving articles by the slug/permalink rather than the title.  There are very few drawbacks other than what to do if people want to edit the title of an existing article.  In many cases it is best not to change the slugline after article creation, within a small window in case your site has been crawled by a search engine.  You don't want to risk losing a search engine placement with an editted post, because you found a small typo and fixed it.

 

So in practice i can make a slug inside php script with preg_replace() using regex and link to that fancy url,  and just remove .php extension with .htaccess file ?

Link to comment
Share on other sites

I was trying to make something for pretty url and i found this working solution

 

.htaccess file

RewriteEngine On
# Removes .php extension from blog.php
RewriteRule ^blog/(.*)?$ blog.php [NC]

blog.php

<?php

// mysql connection
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'mydatabase';

$dbh = new PDO('mysql:host='.$db_host.';dbname='.$db_name.';charset=utf8', $db_user, $db_pass);

$url = explode("/",($_SERVER["REQUEST_URI"]));
$url = str_replace('-', ' ', $url[2]);

if ($url)
{

	$stmt = $dbh->prepare("SELECT * FROM blog WHERE heading = :url");
	$stmt->bindParam(':url', $url);
	$stmt->execute();

	$data = $stmt->fetch();

?>

<h1><?php echo htmlspecialchars($data['heading']); ?></h1>

<p><?php echo htmlspecialchars($data['text']); ?></p>

<?php
} 
// else post all results
else
{
	$stmt = $dbh->prepare("SELECT * FROM blog");
	$stmt->execute();

	$data = $stmt->fetchAll();

	foreach ($data as $key)
	{
?>

<a href="<?php echo str_replace(' ', '-', $key['heading']); ?>"><h1><?php echo $key['heading']; ?></h1></a>
<p><?php echo $key['text']; ?></p>
<hr />

<?php
	}
}

?>

And now my link in url looks like this "localhost/blog/My-first-post"

Link to comment
Share on other sites

Your approach doesn't make a lot of sense.

 

Using titles as IDs is clumsy and forces you to have unique titles, which is rather silly for a blog. It means that you can't use a title ever again, even if the previous post was 10 years ago.

 

A much smarter approach (which is also used in this forum) is to concatenate a numeric ID with the title. In this case, the title is only used for readability and SEO purposes, so it can simply be cut off:

/blog/521-today-i-visited-my-grandmother -> /blog/post.php?id=521

Your slugs should also be improved. There are many other special characters which look weird when they get URL-encoded, not just spaces. You should use a proper library instead of reinventing the wheel.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.