带有 htaccess 规则的 GET 参数中的特殊字符



我的规则是用免费的在线工具生成的。它们工作正常,直到一些特殊字符(如&/-)作为 GET 参数出现在url中。我想获得干净且对 SEO 友好的网址。

我发现了类似的问题,我试图在人们回答时使用正则表达式和标志来解决我的问题,但它仍然不起作用。

如何处理 .htaccess 规则中的 & 和/等特殊字符?

GET 参数不适用于 htaccess 规则

。以及许多其他答案。

我的访问

RewriteEngine On
RewriteRule ^all-books$ /bookIndex.php [L]
RewriteRule ^year/([^/]*)$ /bookIndex.php?year=$1 [L]
RewriteRule ^find-by-first-letter/([^/]*)$ /bookIndex.php?letter=$1 [L]
RewriteRule ^books-online/([^/]*)/about-book$ /book.php?book=$1 [L]

这就是我使用它的方式。

页面和代码:

page: https://example.com/bookIndex.php 
url / a href: https://example.com/all-books
Rule: `RewriteRule ^all-books$ /bookIndex.php [L]`

与 GET 参数相同的页面

url: https://example.com/year/[YEAR HERE]
link: echo "<a href="https://example.com/year/".$row["year"]."">".$row["year"]."</a>";
Rule: RewriteRule ^year/([^/]*)$ /bookIndex.php?year=$1 [L]
url: https://example.com/find-by-first-letter/[FIRST LETTER HERE]
link: echo "<a href="https://example.com/find-by-first-letter/".$row1["letter"]."">".$row1["letter"]."</a>";
Rule: RewriteRule ^find-by-first-letter/([^/]*)$ /bookIndex.php?letter=$1 [L]

正则表达式在那里很好,因为 GET 参数可能只包含第一个字母或数字。我不确定旗帜,我想旗帜很好。

问题所在页面和代码

page: https://example.com/book.php 
url: https://example.com/books-online/[TITLE HERE]/about-book
link: <a href="https://example.com/books-online/".str_replace(' ', '-', $row2['title'])."/about-book">".$row2['title']."</a>
RewriteRule ^books-online/([^/]*)/about-book$ /book.php?book=$1 [L]

如果$row2['title']="The Book"'一切正常,但在以下情况下

$row2['title'] = "K-9000"
$row2['title'] = "24/7"
$row2['title'] = "You & Me"

我在浏览器中收到"页面未正确重定向"错误。 我不知道为什么其他答案的rexeg不起作用,我需要重写康德 %{QUERY_STRING}吗?

那么我用url中的空格更改为"-"的方式呢str_replace(' ', '-', $row2['title'])>?

我确定现在这是错误的方式,因为我必须将空格更改回以获得原始标题以搜索数据库,而标题可能是">K-9000",我不会得到任何结果。

我也应该为此使用htaccess吗,对吧?

您使用的清理str_replace(' ', '-', ...)是不够的,您应该使用另一种高级清理。我创建了以下函数来清理标题,它将用破折号替换所有非字母数字字符:

/**
* Replace all not non-alphanumeric characters with dashes
*
* @var string $title
* @return string
*/
function sanitize_title(string $title) {
$title = strtolower($title);
$title = str_replace('&', 'and', $title);
$title = preg_replace('/([^a-z0-9]+)/', '-', $title);
$title = trim($title, '-');
return $title;
}

然后,当您打印链接时:

<a href="https://example.com/books-online/" . sanitize_title($row2['title']) . "/about-book">".$row2['title']."</a>

例子:

One Hundred Years of Solitude: one-hundred-years-of-solitude
Breakfast at Tiffany's: breakfast-at-tiffany-s
Catch-22: catch-22
Carry On, Jeeves: carry-on-jeeves
Man & His Symbols: man-and-his-symbols
I, Claudius: i-claudius

最新更新