开发者

rewritecond, rewriterule and ignoring extra querystrings

开发者 https://www.devze.com 2023-02-15 16:27 出处:网络
I have an old url: www.example.com/content.aspx?ID=227&ParentID=33&MicrositeID=0&Page=1 that I wish to rewrite to:

I have an old url:

www.example.com/content.aspx?ID=227&ParentID=33&MicrositeID=0&Page=1

that I wish to rewrite to:

www.example.com/product/item

The only important bit is ID=227, everything after that can be stri开发者_C百科pped and is not required for the redirect. I need to not pass any querystrings to the new address, this is basically a hard rewrite from one address to another.

I have my rewrite rule:

RewriteCond %{QUERY_STRING} ^ID=227(.*)$ [NC] 
RewriteRule ^content\.aspx$ http://www.example.com/product/item [R=301,L]

But as I'm a total noob at mod_rewrite I'm struggling - can any htaccess gurus out there help me out?


RewriteCond %{QUERY_STRING} (^|&)ID=(\d+)(&|$) [NC] 
RewriteRule ^content\.aspx$ /product/item/%2? [R=301,L]

A few comments...

There's no need to add .* to match the whole string in this case. As long as you can pinpoint what you want to match, you'll be fine. (^|&) matches either the start of the string or & whereas (&|$) matches either the end of the string or &. This allows id=xxx to be anywhere in the query string, which is good practice. \d matches one digit whereas + is a repetition operator for "one or more".

Furthermore, you don't actually need to include the domain name so long as the resulting page is on the same domain. Just start the resulting string with a / to make it relative to the root level.

%2 means that you're inserting a submatch from the RewriteCond statement rather than the RewriteRule. The latter would be $1, $2, as you might know.

The trailing ? tells the rewrite engine not to append the querystring to the URL. (Don't worry, the question mark won't show up in the redirect URL)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号