Ben
Ben

Reputation: 5777

htaccess rewrite rule for image url

I have the url: http://www.mywebsite.com/i/1Q2GmFuFdZ.jpg

I want to rewrite a rule that makes it go to the file image.php?id=1Q2GmFuFdZ.jpg

In my PHP file, I have this

<?PHP
print_r($_GET);
?>

This is what I have in my htaccess

RewriteEngine On
RewriteRule ([a-zA-Z0-9]+[\.]+[a-z]{3})$ image.php?id=$1

This is the output that I am getting:

Array ( [id] => image.php )

I am not sure what I am doing wrong. I'm no regex pro but I know the basics.

Thanks

EDIT: Forgot to add 0-9 in expression

Upvotes: 2

Views: 2384

Answers (2)

Salman Arshad
Salman Arshad

Reputation: 272386

mod_rewrite rules are applied recursively. Here is what happens when you request 1Q2GmFuFdZ.jpg:

  • 1Q2GmFuFdZ.jpg matches the pattern, becomes image.php?id=1Q2GmFuFdZ.jpg
  • Since filename has changed, another iteration is performed with the re-written URL
  • image.php matches the pattern as well and rewritten as image.php?id=image.php
  • File name or directory did not change so no further iteration is performed
  • End result: image.php?id=image.php

Solution: add this rule:

RewriteEngine On
RewriteRule image\.php$ - [L]
RewriteRule ([a-zA-Z0-9]+\.[a-z]{3})$ image.php?id=$1

The second rule acts as a hand-brake. You need to tweak rule #3 as well.

Upvotes: 3

anubhava
anubhava

Reputation: 786091

Your Rewrite rule is wrong. It should be like this:

RewriteRule ^i/(.+)$ /image.php?id=$1 [L,NC,QSA]

Upvotes: 1

Related Questions