Forum Moderators: phranque

Message Too Old, No Replies

Need help with conditional redirect

         

b8caster

3:30 pm on Sep 4, 2010 (gmt 0)

10+ Year Member



Hello,
I've tried reading through the numerous threads on redirects here, but now my head is spinning. Now I'm just confused even further!

First off, I'm not a stranger to htaccess rules, but since I only meddle with them about once a year, I'm certainly a novice. I'm using Apache 2.2

My issue:

I want to create a redirect for URLs such as these:

domain.com/directory/story.pl?num=2124422
domain.com/directory/story.pl?num=54118584
domain.com/directory/story.pl?num=658475
domain.com/directory/story.pl?num=1283026605
etc.

to point to domain.com/articles

Note that the parameter value is a variable. So I want any URL containing "domain.com/directory/story.pl?num=" to redirect to "domain.com/articles"

However, I want other parameters to redirect elsewhere. For example "domain.com/directory/story.pl?this=" to go to a specific URL, and "domain.com/directory/story.pl?that=" to go to another, etc.

So for the first rule, I was thinking something like this:

RewriteCond %{HTTP_HOST} ^domain.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.domain.com$
RewriteCond %{REQUEST_URI} ^/directory/story.pl
RewriteCond %{QUERY_STRING} ^num=xyz$
RewriteRule ^(.*)$ /articles? [R=301,L]

But it doesn't take into account the variable. Can I just replace "xyz" with "?" or is there a better way to do this?

jdMorgan

2:05 am on Sep 5, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I doubt that your stated requirements are what you really want (or need), but the code can be much simplified:

RewriteCond %{QUERY_STRING} ^num=[0-9]+$
RewriteRule ^directory/story\.pl$ http://www.example.com/articles? [R=301,L]

You only need to look at %{HTTP_HOST} if you're hosting multiple domains or subdomains in this same filespace. And even in this case, you should have a separate rule to canonicalize www.domain.com requests by redirecting them to domain.com, making a test for both the www- and non-www hostnames unnecessary in this previous rule.

See the regular expressions tutorial cited in our Apache Forum Charter for more information on creating regex patterns.

Jim

[edited by: jdMorgan at 5:43 pm (utc) on Sep 10, 2010]

b8caster

1:55 pm on Sep 5, 2010 (gmt 0)

10+ Year Member



That did the trick! Thank you very much!