1

我有这样的网址:

siteurl.com/category.php?id=6&name=internet

我想做一个 301 重定向到

siteurl.com/category/6/internet/

我试过没有成功:

RewriteRule ^category.php?id=([^&]*)&name=([^&]*) /category/$1/$2/ [R=301,L]

有关它的更多信息:谷歌上的重复内容。htaccess 还是 robots.txt?

有什么帮助吗?


额外编辑;该页面也可以通过siteurl.com/category.php?id=6(没有名称查询)访问。处理这个问题的最佳方法是什么?将这种 URL 重定向到主页?如果是这样,我该怎么做?

4

1 回答 1

1

查询字符串不会出现在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]
于 2012-10-11T00:31:18.240 回答