查询字符串不会出现在RewriteRule
表达式中。相反,您必须通过%{QUERY_STRING}
与RewriteCond
匹配。
RewriteEngine On
# Capture the id and name into %1 and %2 from the query string
RewriteCond %{QUERY_STRING} ^id=(\d+)&name=([a-zA-Z-]+)
# If the query string does not include noredirect=
# This protects against a rewrite loop when attempting to 301 redirect the ugly URL
RewriteCond %{QUERY_STRING} !noredirect=
# Rewrite category.php to /category/id/name
RewriteRule ^category\.php /category/%1/%2/? [L,R=301]
的?
时,只需要避免在URL的末尾reapeating查询。
# I assume you also have the following rule, which configures the pretty URL in the first place
# Then in the rule which points the pretty URL to the real internal one, add
# the fake query string param noredirect=1, which won't actually be used by PHP. It just
# matches in the rules above to prevent rewriting when present
RewriteRule ^category/(\d+)/([^/]+) category.php?id=$1&name=$2&noredirect=1 [L]
现在它重定向到正确的url,但页面没有显示,它给出错误“不正确的重定向”。在Firefox上。 –
@LucasMatos如果您还有一条指向实际URL(您试图避免的URL)的规则来处理脚本,您可能会得到一个重定向循环。我会在上面发布一个技巧。 –
非常感谢你,你做到了。只有一个xtra问题:URL也可以通过'siteurl/category.php?id = 6'访问(查询名称)。我不认为只用一个查询就可以做出同样的重定向,对吧?那么,我如何将这种URL重定向到主页? –