dtra49684 2012-07-26 02:44
浏览 33
已采纳

麻烦保留$ _GET变量

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!

  • 写回答

1条回答 默认 最新

  • dongtaoxue4674 2012-07-26 02:54
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?