views:

448

answers:

3

Though .htaccess, I want to redirect /page/var1/var2 to ./page.php?var1=var1&var2=var2. This is very easy BUT I want to make it so /page/var1 also redirects to ./page.php?var1=var1 (without having the var2). The only way I'm doing this is:

RewriteRule page/(.*)$ ./page.php?var1=$1
RewriteRule page/(.*)/(.*)$ ./page.php?var1=$1&var2=$2

As you can see it's very redundant, and I have a ton of lines like this, so it gets very messy. Any way to define "optional" parts?

+1  A: 

mod_rewrite is not well suited to such heavy lifting, leave that to your PHP app.

 RewriteRule page/(.*)$ ./page.php?vars=$1

and somewhere near the beginning of page.php:

 <?php
 $vars = explode('/',$_GET['vars']);

Voila, you have an array of your vars; now you could do some processing there to see what is required/optional for your app and react accordingly.

Piskvor
Thank you, so basically, it is not possible to do it with .htaccess?
Yifan
It is possible, but as you have already found out, it is not very practical.
Piskvor
+1  A: 

The best approach is to just hand everything over to your PHP script.

I wrote an article on how to do friendly URLs, which covers this in more detail.

HM2K
A: 

The expression .* matches both var1 and var1/var2 thus the first rule is applied on both.

So you have to specify it that the first rule only matches var1. This can be done by replacing . (any character) by [^/] (any character except /). So try this:

RewriteRule ^page/([^/]+)$ ./page.php?var1=$1
RewriteRule ^page/([^/]+)/([^/]+)$ ./page.php?var1=$1&var2=$2

Edit   You can also write this in one rule:

RewriteRule ^page/([^/]+)(/([^/]+))?$ ./page.php?var1=$1&var2=$3
Gumbo
I think mod_rewrite stops when it finds a match, so as long as I put the two vars one before the one var one, it will be fine, but thanks for the heads up.
Yifan
THANK YOU! This was exactly what I was looking for.
Yifan