skip to Main Content

I want to test if file exists for both the rules at the bottom, but it only seems to work for the first one. The second rule would wrongly match my /style.css file and display the php page instead of style.css.

Isn’t it supposed to test if file exists for all next rules until the [L] flag ?

RewriteEngine On

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

RewriteRule ^([^/]+)/([^/]+)/?$ browse_folder.php?username=$1&folder=$2
RewriteRule ^([^/]+)/?$ browse_user.php?username=$1 [L]

If I repeat the file_exists test before each of the two lines it works as expected.

RewriteEngine On

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

RewriteRule ^([^/]+)/([^/]+)/?$ browse_folder.php?username=$1&folder=$2

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

RewriteRule ^([^/]+)/?$ browse_user.php?username=$1 [L]

2

Answers


  1. Isn’t it supposed to test if file exists for all next rules until the
    [L] flag ?

    No, it’s not. RewriteCond‘s are applied to the very first-next RewriteRule only. From the official documentation:

    The RewriteCond directive defines a rule condition. One or more
    RewriteCond can precede a RewriteRule directive. The following rule is
    then only used if both the current state of the URI matches its
    pattern, and if these conditions are met.

    Note the can precede a RewriteRule

    Workaround

    If you don’t want to repeat yourself, you can proceed as following:

    RewriteEngine On
    
    # Don't touch existing files/folders
    RewriteCond %{REQUEST_FILENAME} -d [OR]
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule ^ - [L]
    
    # Those rules are only applied to non-existing files/folders
    RewriteRule ^([^/]+)/([^/]+)/?$ browse_folder.php?username=$1&folder=$2
    RewriteRule ^([^/]+)/?$ browse_user.php?username=$1 [L]
    
    Login or Signup to reply.
  2. RewriteCond is only applicable to next RewriteRule. You can make a separate rule to skip all files and directories on top of other rewrite rules.

    RewriteEngine On
    
    # skip all existing files and directories
    RewriteCond %{REQUEST_FILENAME} -d [OR]
    RewriteCond %{REQUEST_FILENAME} -f 
    RewriteRule ^ - [L]
    
    RewriteRule ^([^/]+)/([^/]+)/?$ browse_folder.php?username=$1&folder=$2 [L,QSA]
    
    RewriteRule ^([^/]+)/?$ browse_user.php?username=$1 [L,QSA]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search