首页 > 解决方案 > 带有 htaccess 规则的 GET 参数中的特殊字符

问题描述

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

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

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

GET 参数不适用于 htaccess 规则

...以及许多其他答案。

我的 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]

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

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

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

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

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

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

标签: phpregex.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

推荐阅读