RewriteRule 301重定向具有多个查询字符串的网址

时间:2012-10-11 00:28:30

标签: .htaccess mod-rewrite

我的网址如下:

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]

有关它的更多信息:Duplicated content on google. htaccess or robots.txt?

任何帮助?


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

1 个答案:

答案 0 :(得分:1)

查询字符串不会出现在RewriteRule表达式中。相反,您必须通过RewriteCond%{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]