Search code examples
phpapache.htaccessmod-rewrite

I am trying to simulate else in mod_rewrite


I have this code:

RewriteEngine On

# Delete .php extension
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^.]+)$ $1.php [L]

# If file does not exist redirect to error.php
RewriteCond %{REQUEST_FILENAME}.php !-f
RewriteRule ^(.*)$ error.php [L]

# Friendly URL
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^user/(.*)$ user.php?ID=$1 [L] 

Problem: The second statement works by Itself but when I add the first statement the second always redirects me to error.php.

Possible solution: I thought about doing something like this:

if(RewriteCond %{REQUEST_FILENAME}.php !-f)
    RewriteRule ^(.*)$ error.php [L]
else
    RewriteRule ^user/(.*)$ user.php?ID=$1 [L] 

I have been a while trying to figure out by myself how to make It work but I can't. A would appreciate some help.


Solution

  • Have it like this:

    Options -MultiViews
    RewriteEngine On
    
    # Friendly URL for user/...
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^user/(.*)$ user.php?ID=$1 [L,QSA,NC] 
    
    # Add .php extension internally
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{DOCUMENT_ROOT}/$1.php -f
    RewriteRule ^([^.]+?)/?$ $1.php [L]
    
    # If there is no rewrite and 
    # files/directory don't exist then forward to error.php
    RewriteCond %{ENV:REDIRECT_STATUS} ""
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . error.php [L]