php - URL 重写,包括标题

标签 php .htaccess

最初我成功使用 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/

相关文章:

php - 子目录的 URL 无法正确重写

javascript - Highcharts 饼图悬停时不透明度发生变化

php - 从 Laravel 5.1 中的通用数据库查询获取 Eloquent 模型的实例

PHP 无法访问新创建的 zip 文件

javascript - 我们可以在组合图表中创建曲线吗?

Apache2 mod_expires 不工作

php - 如何将 url 更改为子文件夹

apache - 使用 .htaccess 将特定 IP 地址重定向到我主页的特殊页面

javascript - 更新记录时缺少可选字段值的正确明确的服务器端行为应该是什么?

.htaccess RewriteRule 在浏览器中无需更改 URL