【问题标题】:Issue with .htacces rewrite rules and special characters.htaccess 重写规则和特殊字符的问题
【发布时间】:2013-10-27 21:24:26
【问题描述】:

我使用一些重写规则来为论坛制作可读的 url。例如,如果您发布主题标题为“嘿,您觉得这辆新车怎么样?”的新主题。我将创建一个这样的链接:forum/cars/51-Hey-what-do-you-think-of-this-new-car-? 其中 51 是主题 ID。

在我的 .htaccess 中,我使用了这个重写规则:

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^forum/([0-9-a-z]+)/?$ forum/list_topics.php?key=$1 [L]
RewriteRule ^forum/([0-9-a-z]+)/([0-9]+)?$ forum/list_topics.php?key=$1&page=$2 [L]
RewriteRule ^forum/([0-9-a-z]+)/([0-9]+)-(.*)/?$ forum/list_post.php?topic=$2 [L]

所以这很好用,除非我发布带有这些字符的主题标题:+"*ç%&/()=?'^

我使用 php 函数来创建 url,它是:

$url_topic = str_replace(' ', '-', $url_topic); //replace space with -
$url_topic = urlencode($url_topic);//encode url

在这种情况下,$url_topic 的值是:34-%2B%22%2A%C3%A7%25%26%2F%28%29%3D%3F%27%5E 但是当我点击它时,出现以下错误:

Not Found

The requested URL /forum/cars/34-+"*ç%&/()=?'^ was not found on this server.
Apache/2.2.22 (Ubuntu) Server at localhost Port 80

我错过了什么?

谢谢

【问题讨论】:

    标签: php .htaccess mod-rewrite url-rewriting special-characters


    【解决方案1】:

    URL 转义字符串在您使用 RewriteRule 隐式比较的字符串中进行解码。这意味着如果你捕获它们,它们已经被解码了!。

    IMO,最好的解决方案是针对 %{THE_REQUEST} 进行捕获,它仍然像客户端那样进行 URL 编码。这需要 1 个 addl RewriteCond。

    第二个选项是使用 [B] 标志来重新转义反向引用。我不喜欢这个,因为重新转义并不真正了解替换的去向。

    【讨论】:

    • 嗨,谢谢你的解释,但你能添加一个我必须做的 RewriteCond 的例子吗?否则我想我会简单地从我的 php 字符串中删除特殊字符..这是我认为最好的解决方案
    猜你喜欢
    • 2013-01-11
    • 1970-01-01
    • 2014-07-17
    • 2014-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多