Forum Moderators: phranque

Message Too Old, No Replies

Rewrite Rules For An Underscore

         

HoboTraveler

6:31 pm on Dec 18, 2008 (gmt 0)

10+ Year Member



Hi All,

I need to create a htaccess rewrite rule and point the two URLs separately to different files.

whateverdomain.com/dir/foo_bar/
whateverdomain.com/dir/foo/

In the first instance I need to say the pattern with the underscore would rewrite the variables to var1.php and in the second case the URL without the _ would rewrite variables to var2.php. dir is a directory that would never have any underscores.

foo_bar and foo can contain numbers. Any ideas on how to do this?

Thanks

g1smd

7:17 pm on Dec 18, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



What have you tried so far?

It should be fairly easy because there is a clear difference in the two patterns to be matched.

HoboTraveler

7:06 am on Dec 19, 2008 (gmt 0)

10+ Year Member



This is what I have so far:

What happens though is, this URL whateverdomain.com/dir/foo_bar/ with the underscore resolves to the second rule instead of the first.

How do I force it to use the first rule so that foo_bar would be var1=foo and var2=bar ?

RewriteRule ^dir/([^/\.]+)/([^/\.]+)_([^/\.]+)/?$ /var1.php?dir=dir&var1=$1&var2=$2 [NC] [L]

RewriteRule ^dir/([^/\.]+)/?$ /var2.php?dir=dir&var1=$1 [NC] [L]

HoboTraveler

1:38 pm on Dec 19, 2008 (gmt 0)

10+ Year Member



I figured the problem. There was an extra ([^/\.]+)

I got rid of that and it works great.

Thanks!

jdMorgan

6:35 pm on Dec 19, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The syntax of your rules is invalid (see flags) and the second rule could be made more robust -- Add the underscore to the excluded character group:

RewriteRule ^dir/([^/\.]+)_([^/\.]+)/?$ /var1.php?dir=dir&var1=$1&var2=$2 [NC,L]
#
RewriteRule ^dir/([^/_\.]+)/?$ /var2.php?dir=dir&var1=$1 [NC,L]

Also, realize that using [NC] on these rules allows mis-cased "dir" URLs to resolve directly to a "page", and that same page will therefore appear at nine different URLs. This is a duplicate-content problem, and can cause search ranking problems. You can cure that problem by removing [NC] from both rules, and redirecting mis-cased requests like this:

RewriteCond %{REQUEST_URI} !^/dir/
RewriteRule ^dir/(.*)$ http://www.example.com/dir/$1 [NC,R=301,L]

Note that the rule pattern accepts any case for the letters in "dir" but the RewriteCond prevents a redirect if the case is already correct.

Unfortunately, there is no good way to detect casing errors on the path appended to "/dir/" using mod_rewrite -- And this is one reason why you should be very careful not to allow mis-cased URLs to resolve in the first place... Either redirect them, or let them go 404-Not Found.

Jim