查询字符串不会出现在RewriteRule
表达式中。相反,您必须在RewriteCond
, via中匹配它%{QUERY_STRING}
。
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 末尾重复查询。
# 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]