【发布时间】:2019-06-07 20:08:32
【问题描述】:
我的规则是使用免费的在线工具生成的。它们可以正常工作,直到出现一些特殊字符,例如 & / - 在 url 中显示为 GET 参数。我想获得干净且对 SEO 友好的网址。
我发现了类似的问题,我尝试在人们回答时使用正则表达式和标志来解决我的问题,但它仍然不起作用。
How to handle special characters like & and / in .htaccess rules?
GET parameter doesn't work with htaccess rules
...以及许多其他答案。
我的 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]
Regex 在那里很好,因为 GET 参数可能只包含第一个字母或数字。我不确定flag,我猜flag很好。
问题所在的页面和代码
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 不起作用,我需要 RewriteCond %{QUERY_STRING} 吗?
我用str_replace(' ', '-', $row2['title'])> 将 url 中的空格更改为“-”的方式如何?
我现在确定这是错误的方式,因为我必须将空格改回以获取原始标题以搜索数据库,而标题可能是“K-9000”,我不会得到任何结果。
我也应该使用 htaccess,对吗?
【问题讨论】:
-
如果您想在 URL 中使用非 urlsafe 字符,您需要
urlencode()该数据。