开发者

URL Rewriting including title

Initially i succeed to rewrite the url using id

with the htaccess code:

RewriteRule ^link/([0-9]+)\.html$ sub_index.php?link_id=$1 

and link code

a href="link/id.html"> 

It displays successfully :

Then i tried to make url like this: mysite.com/link/Trekking in Nepal/6.html where "Trekking in Nepal" is a title in database

I wrote htaccess code:开发者_JS百科

RewriteRule ^link/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ sub_index.php?link_id=$1 

and link code:

a href="link/title/id.html">

I cannot successfully rewrite my url to the desired format and get the message The requested url is not found on the server

Also when i searched in other sites, i didn't see space, the title is written like "Trekking-in-Nepal".

I am wondering, need help

Thanks


First, your rewrite code is not correct:

RewriteRule ^link/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ sub_index.php?link_id=$1

Your link_id is $2, your title is $1. So you should use:

RewriteRule ^link/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ sub_index.php?link_id=$2

Then you should use a slug function for your title, so it's more url friendly. I use something like this:

function slug($string, $spaceRepl = "-") {
  // Replace "&" char with "and"
  $string = str_replace("&", "and", $string);

  // Delete any chars but letters, numbers, spaces and _, -
  $string = preg_replace("/[^a-zA-Z0-9 _-]/", "", $string);

  // Optional: Make the string lowercase
  $string = strtolower($string);

  // Optional: Delete double spaces
  $string = preg_replace("/[ ]+/", " ", $string);

  // Replace spaces with replacement
  $string = str_replace(" ", $spaceRepl, $string);

  return $string;
}

slug("Trekking in Nepal") will be trekking-in-nepal, so your link will be:

/link/trekking-in-nepal/6.html

It should work then with your rewrite code.

Also, I like to rewrite my links like this:

/link/trekking-in-nepal-6.html

For this I use the following:

RewriteRule ^link/([a-zA-Z0-9_-]+)-([0-9]+)\.html$ sub_index.php?link_id=$2

Good luck!


Try:

RewriteRule ^link/([a-zA-Z0-9_- ]+)/([0-9]+)\.html$ sub_index.php?link_id=$2 

However you should use rawurlencode when you output the title, in order for it to work properly on any kind of browser.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜