How to strip out part of a URL with mod_rewrite
I am trying to redirect from this:
www.mysite.com/product.html?item=example
to:
www.mysite.com/example
I have this rewrite rule in my .htaccess 开发者_StackOverflowfile but it isn't working:
RewriteRule ^/product\.html\?item=(.*)$ /$1 [R=301,L]
Any help is much appreciated.
Here's what I have now:
RewriteCond %{QUERY_STRING} ^item=(.*)$
RewriteRule ^/product\.html$ /%1 [R=301,L]
And here is the Final result after I got rid of forward slash at the beginning of the rule and added a question mark at the end of the rule to get rid of the query string:
RewriteCond %{QUERY_STRING} ^item=(.*)$
RewriteRule ^product\.html$ /%1? [R=301,L]
Because you are in an .htaccess
file, you'll want to remove the leading slash from your RewriteRule
:
RewriteCond %{QUERY_STRING} ^item=(.*)$
RewriteRule ^product\.html$ /%1? [R=301,L]
In reference to the query string being passed through, the Apache 2.2 documentation for mod_rewrite says this about it:
Modifying the Query String
By default, the query string is passed through unchanged. You can, however, create URLs in the substitution string containing a query string part. Simply use a question mark inside the substitution string to indicate that the following text should be re-injected into the query string. When you want to erase an existing query string, end the substitution string with just a question mark. To combine new and old query strings, use the
[QSA]
flag.
So as you discovered, you need only to add a ?
after the substitution.
精彩评论