查詢字符串不會出現在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重定向到主頁? –