Sunday, May 1, 2011

Mod Rewrite and PHP

I am trying to redirect pages using mod_rewrite to the pages with some variables (for using them with PHP's $_GET).

To give an example with few lines:

  • When the user enters /c/stg it redirects to item_show.php?id=$1&f=1 (where f is page number).
  • When the user enters /c/stg/2 it redirects to the second page with show.php?id=$1&f=$2.

I think there are no errors or misuses of these in my file but, here's what I want:

I want user to enter /string directly to go item_show.php?id=$1&f=1 with $1 is our string of course...

But when I change my file by removing the /c/ part from RewriteRule it starts giving errors in all other directories and doesn't read any files (my.css) even though I have already defined a RewriteCond %{REQUEST_FILENAME} !-f...

Do you have any suggestions? Or how can I made this system possible with any method?

Options FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

#user
RewriteRule ^u/([^/]+)/?$ profile.php?username=$1 [L,NC]

#marked
RewriteRule ^marked/([^/]+)/?$ item_marked.php?id=$1 [L,NC]

#content
RewriteRule ^c/([^/]+)/?$ item_show.php?id=$1&f=1 [L,NC]
RewriteRule ^c/([^/]+)/([^/]+)/?$ item_show.php?id=$1&f=$2 [L,NC]
From stackoverflow
  • RewriteCond directives do only belong to the first following RewriteRule directive. So in your case the two RewriteCond direcitves are only applied to the first RewriteRule directive and not to the others.

    But you could use this abortion rule to quit the rewrite process if the request can be mapped to an existing file or directory:

    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]
    

    This would cause that following rules are only tested if the request cannot be mapped directly to an existing file or directory.

  • Am I wrong if RewriteCond only are passed on to the first RewriteRule??

    Try this instead:

    Options FollowSymLinks
    RewriteEngine On
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    
    #user
    RewriteRule ^u/([^/]+)/?$ profile.php?username=$1 [L,NC]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    #marked
    RewriteRule ^marked/([^/]+)/?$ item_marked.php?id=$1 [L,NC]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    #content
    RewriteRule ^c/([^/]+)/?$ item_show.php?id=$1&f=1 [L,NC]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^/]+)/([^/]+)/?$ item_show.php?id=$1&f=$2 [L,NC]
    

    Cheers,

    jnbn : I already figured it out today but thanks Josso :)
    Josso : I'm just happy that I got a point so I can vote. :p A lot of the questions here are quite out of my knowledge. :(

0 comments:

Post a Comment