Nadav S.
Nadav S.

Reputation: 2459

htaccess - multiple rewrites & capture groups

I'm trying to handle multiple areas of an application, but the URLs are not being rewrited as expected.

This is the .htaccess file:

RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule ^division/(.*)/section/(.*)$ ./index.php?division=$1&section=$2
RewriteRule ^division/(.*)$ ./index.php?division=$1
RewriteRule ^area/(.*)$ ./index.php?area=$1

What's expected:

  1. If the URI matches division/some_division/section/some_section rewrite to index.php?division=some_division&section=some_section

  2. If no section (section/some_section) is defined, go to the second rule -

    If the URI matches division/some_division rewrite only to index.php?division=some_division

  3. If no division is defined, and the URI matches area/some_area rewrite to index.php?area=some_area

I'm almost sure I can combine the two first rules, I've tried this regex but it didn't work:

^division/(.*)( /section/(.*) )?$

It supposed to make /section/some_section an optional value.

Unfortunately nothing works. Any ideas?

Upvotes: 0

Views: 3758

Answers (1)

Ωmega
Ωmega

Reputation: 43703

RewriteEngine On 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^division/(.*)/section/(.*)$ ./index.php?division=$1&section=$2 [QSA,L]
RewriteRule ^division/(.*)$              ./index.php?division=$1            [QSA,L]
RewriteRule ^area/(.*)$                  ./index.php?area=$1                [QSA,L]

Upvotes: 2

Related Questions