Adrian33
Adrian33

Reputation: 291

Clean URL with multiple variables

I plan to receive a number of urls. What mod rewrite rules would I use to make the following conversions for incoming urls:

http://domain.com/i/ => 
http://domain.com/index.php

http://domain.com/i/b/233223/c/23333 => 
http://domain.com/index.php?b=233223&c=23333

http://domain.com/i/dd/9844kjhf/fj/djP756/ee/kjhKJH => 
http://domain.com/index.php?dd=9844kjhf&fj=djP756&ee=kjhKJH

http://domain.com/r/ => 
http://domain.com/restore.php

http://domain.com/w/place/chicago =>
http://domain.com/withold.php?place=chicago

http://domain.com/w/ =>
http://domain.com/withold.php

Basically, the first portion after the domain corresponds to a page, the rest is a set of any number of parameters to be passed.

Upvotes: 1

Views: 1862

Answers (2)

Jon Lin
Jon Lin

Reputation: 143866

Try:

# If the URI is just /i/, rewrite to index.php
RewriteRule ^i/?$ /index.php [L]

# If the URI is /i/ plus some paths, rewrite the paths into query string and let rewrite engine loop
RewriteRule ^i/([^/]+)/([^/]+)(/?.*)$ /i$3?$1=$2 [L,QSA]

This will take as many path nodes as the internal recursion limit is set to, by default it's 10. That means by default you can have up to 9 sets of parameters unless you up this limit. So:

http://example.com/i/a/1/b/2/c/3/d/4/e/5/f/6/g/7/h/8/j/9

will first match the 2nd rule, and continue to loop:

1. /i/b/2/c/3/d/4/e/5/f/6/g/7/h/8/j/9?a=1
2. /i/c/3/d/4/e/5/f/6/g/7/h/8/j/9?b=2&a=1
3. /i/d/4/e/5/f/6/g/7/h/8/j/9?c=3&b=2&a=1
4. /i/e/5/f/6/g/7/h/8/j/9?d=4&c=3&b=2&a=1
etc.

until finally you're left with

/i?j=9&h=8&g=7&f=6&e=5&d=4&c=3&b=2&a=1

and the first rule gets applied and you should finally end up with:

/index.php?j=9&h=8&g=7&f=6&e=5&d=4&c=3&b=2&a=1

Upvotes: 3

Juan Cullen
Juan Cullen

Reputation: 98

As you could have an unlimited number of parameters in your URL it would be better to create a script in you application to parse them.

You could use .htaccess to direct all incoing requests to a routing file ( e.g. index.php )

Options -MultiViews
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [QSA,L]

Then run something like PHP explode() to parse the URL

Upvotes: 1

Related Questions