1

I've made an php script that builds an image and I want to use htaccess for a nice url

The script builds an image depending on some variables:

for example:

All options given
php url:  image.php?width=300&height=400&color=red&var1=something&var2=somethingelse
nice url: image-w300-h400-cred-v1something-v2something.png

Few options given
php url:  image.php?var1=something&color=black
nice url: image-v1something-cblack.png

I know how to build a rewriteRule for every combination but isn't there a way to automate that?

2 Answers 2

4

Probably the simplest solution:

RewriteRule ^image-(.+)\.png$ image.php?params=$1

Then parse $_GET['params'] in PHP.

Sign up to request clarification or add additional context in comments.

3 Comments

then it's all in one parameter, what is the best way to split them up again?
explode('-', $_GET['params']), then parse each individual parameter according to whatever rules you think up.
I'd think that is the easiest, or at least the most maintainable, solution.
1

If you always put your params in the same order, you can use this kind of rule :

RewriteRule 
    ^image(-w[0-9]+)?(-h[0-9]+)?(-c[a-z]+)?(-v1[A-Za-z0-9-]+)?(-v2[A-Za-z0-9-]+)?\.png$ 
    image.php?width=$1&height=$2&color=$3&var1=$4&var2=$5 [L]

EDIT :

RewriteRule 
    ^image(-w([0-9]+))?(-h([0-9]+))?(-c([a-z]+))?(-v1([A-Za-z0-9-]+))?(-v2([A-Za-z0-9-]+))?\.png$ 
    image.php?width=$2&height=$4&color=$6&var1=$8&var2=$10 [L]

EDIT 2 to prevent $10 problem :

RewriteRule 
    ^image(?:-w([0-9]+))?(?:-h([0-9]+))?(?:-c([a-z]+))?(?:-v1([A-Za-z0-9-]+))?(?:-v2([A-Za-z0-9-]+))?\.png$ 
    image.php?width=$1&height=$2&color=$3&var1=$4&var2=$5 [L]

4 Comments

This looks like what i'm searching for but the variables contain the prefixes for example width=-w200, it should be width=200
The problem with this is that you'll have to supply the arguments in the exact order or it won't match. That's not necessarily hard, but query parameters should not depend on a particular order. Also, this is pretty hard to maintain if you keep adding/changing parameters.
@deceze I agree, that's a constraint, but for SEO needs, you should never have two differents urls for the same page, then use ordered params seems to be a good practice.
$10 does not work because $10 will be $1 and 0 for example $1 = black then $10 becomes black0, i will edit your post for the solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.