Last Updated on April 29, 2021 by Amit

Exclude files and folders from RewriteRule

With RewriteRules we can use conditions to check if a file or folder exists.

To check the existence of a file we us the -f oprator . The “-f” represents that the file being checked exists in the server filesystem.

We use !-f when we do the opposite. The !-f means that the file being checked doesn’t exist.

The same method is used to test a directory with mod-rewrite.
We use -d to check if it exists and !-d when we are doing a negative test.

When we write a RewriteRule to rewdirect or rewrite URLs we often put one or more RewriteConds above a rule. We use conditions so that the rule can execute based on those conditions.
Two commonly used conditions with RewriteRule are :

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

The first condition checks the requested URI string and looks in the filesystem to see if it doesn’t exist as file.

The second condition checks the requested URI string and looks in the filesystem to see if it doesn’t exist as dir.

These two conditions if used with a RewriteRule can prevent your real files/folders from being rewritten by the rule.
See the following code example :

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) /index.php [L]

The rule above has a catch-pattern (.*) and matches any incoming URL paths. But since we have added conditions to exclude files and folder, the rule will only rewrite requests that don’t exist or not a file or directory.

If you remove these two conditions from the rule above , then the rule will also rewrite your existent files and folders to /index.php even the index.php will get rewritten to itself which can cause a infinite loop error in htaccess.

The two conditions :

  1. RewriteCond %{REQUEST_FILENAME} !-f
  2. RewriteCond %{REQUEST_FILENAME} !-d

are important when you are using a rule with catch-all pattern or when you don’t want your existent files or folder to redirect to the rule’s target.

Related : Htaccess mod-rewrite tutorial for beginners .

How useful was this post?

Click on a star to rate it!

Average rating 2 / 5. Vote count: 1

No votes so far! Be the first to rate this post.