最初我成功使用 id 重写了 url
使用 htaccess 代码:
RewriteRule ^link/([0-9]+)\.html$ sub_index.php?link_id=$1
和链接代码
a href="link/id.html">
显示成功:
然后我尝试制作这样的网址: mysite.com/link/尼泊尔徒步旅行/6.html 其中“尼泊尔徒步旅行”是数据库中的标题
我编写了htaccess代码:
RewriteRule ^link/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ sub_index.php?link_id=$1
和链接代码:
a href="link/title/id.html">
我无法成功地将我的网址重写为所需的格式并获取消息 在服务器上找不到请求的 url
另外,当我在其他网站搜索时,我没有看到空格,标题写的是“Trekking-in-Nepal”。
我想知道,需要帮助
谢谢
最佳答案
首先,你的重写代码不正确:
RewriteRule ^link/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ sub_index.php?link_id=$1
您的 link_id 是 $2,您的标题是 $1。所以你应该使用:
RewriteRule ^link/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ sub_index.php?link_id=$2
那么你应该为你的标题使用 slug 函数,这样它对 url 更友好。我用这样的东西:
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")
将是 trekking-in-nepal
,因此您的链接将为:
/link/trekking-in-nepal/6.html
它应该可以与您的重写代码一起使用。
此外,我喜欢像这样重写我的链接:
/link/trekking-in-nepal-6.html
为此,我使用以下内容:
RewriteRule ^link/([a-zA-Z0-9_-]+)-([0-9]+)\.html$ sub_index.php?link_id=$2
祝你好运!
关于php - URL 重写,包括标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6940644/