OneThreeSeven
OneThreeSeven

Reputation: 422

Trouble preserving $_GET variables

I want to redirect from /gallery/X to gallery.php?category=X

But when I actually goto the address, my old $_GET variable 'category' is transformed into the form:

$_GET['category'] = "X.php/X"   

This is what my .htaccess looks like:

RewriteBase /

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

RewriteCond  %{REQUEST_FILENAME} !-d
RewriteCond  %{REQUEST_FILENAME} !-f
RewriteRule ^gallery/(.*)$ /gallery.php?category=$1 [L]

I am very bad at RegEx and no almost nothing about .htaccess. I have been trying to play around with this rewrite rule to preserve the $_GET variables, but nothing I do seem to work. What am I supposed to do here?

Thanks!

Upvotes: 2

Views: 86

Answers (1)

Mike Mackintosh
Mike Mackintosh

Reputation: 14235

Move your rules around:

RewriteEngine on
RewriteBase /

RewriteCond  %{REQUEST_FILENAME} !-d
RewriteCond  %{REQUEST_FILENAME} !-f
RewriteRule ^gallery/(.*)$ /gallery.php?category=$1 [L]

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

Also, add QSA to your action, [L,QSA]. This appends the query string during the redirect, so it should keep your previous data.

Explanation:

Your rewrites need to be in a specific order because the [L] option is like making a completely new request to the server. So, when your request for gallery/X came in, it rewrote your request to /gallery.php?category=X. When this page was requested by the server, it matched your first rule, which means it was being seen as X.php/X which was then being returned to the original request as the extra $1.

Sounds confusing but I think that's what was going on.

Upvotes: 3

Related Questions