Three-level Mod_rewrite?

Discuss practical ways rearrange URLs using mod_rewrite.

Three-level Mod_rewrite?

Postby airplaneflyer » Tue Aug 05, 2008 4:01 am

I've got a mod_rewrite working perfectly using:

Code: Select all
RewriteRule (.*)/(.*) ./index.php?area=$1&content=$2


I then add:

Code: Select all
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !\..+$
RewriteCond %{REQUEST_URI} !/$

RewriteRule (.*) http://www.mydomain.com/$1/ [NC,QSA,L]


to this, to ensure trailing slashes.

Now what I want to do is add one more level of subfolder to some of the folders - so I could have

www.mydomain.com/web/tutorials/using-htaccess

which when rewritten should give (for example)

www.mydomain.com/index.php?area=web&content=tutorials&subcontent=using-htaccess

I've tried the obvious -

Code: Select all
RewriteRule (.*)/(.*)/(.*) ./index.php?area=$1&content=$2&subcontent=$3


but that won't work for the original URLs with only one extra element - eg for

www.mydomain.com/blog

when I get a "can't find /blog/" 404 error.

Is there a way to use three levels?

Many thanks for any help
airplaneflyer
 
Posts: 3
Joined: Tue Aug 05, 2008 2:58 am

Postby richardk » Wed Aug 06, 2008 3:21 pm

It won't work because it's looking for two slashes (not including the first one).
Code: Select all
Options +FollowSymLinks

RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule [^/]$ %{REQUEST_URI}/ [R=301,L]

RewriteRule ^([^/]+)(?:/([^/]+)(?:/([^/]+))?)?/?$ /index.php?area=$1&content=$2&subcontent=$3 [QSA,L]

The surrounding ()? makes the two /([^/]+) optional.
?: matches the () not create a backreference (variable) so $2 is still for the second ([^/]+).
richardk
 
Posts: 8800
Joined: Wed Dec 21, 2005 7:50 am

Postby airplaneflyer » Wed Aug 06, 2008 10:14 pm

That's brilliant - many thanks richardk. As lots of people have already said here (but it's true), you're a genius!

To take the question one step further - is there a way to make the depth infinite? In other words, having a mod_rewrite that can cope with an undefined number of levels? I would guess that would mean some sort of loop in the htaccess.

I'm not planning on using such a loop (at the moment) - just wondering if it's possible from a theoretical point of view.
airplaneflyer
 
Posts: 3
Joined: Tue Aug 05, 2008 2:58 am

Postby richardk » Thu Aug 07, 2008 12:52 pm

If you wanted infinite levels, i would explode() the REQUEST_URI variable in your PHP.
richardk
 
Posts: 8800
Joined: Wed Dec 21, 2005 7:50 am

Postby airplaneflyer » Fri Aug 08, 2008 9:54 pm

That's interesting. Thanks.
airplaneflyer
 
Posts: 3
Joined: Tue Aug 05, 2008 2:58 am


Return to Friendly URLs with Mod_Rewrite

Who is online

Users browsing this forum: Google [Bot] and 7 guests

cron