Mod rewrite directory if file / folder not found

I have a folder named "folder1" in the root directory

www.domain.com/ www.domain.com/folder1

I need to redirect all requests to www.domain.com that turned into 404 error to folder1. For instance:

www.domain.com/a_file.txt

If the a_file.txt file does not exist, look in folder1:

www.domain.com/folder1/a_file.txt

I want this to work the same for subdirectories, for example:

www.domain.com/a_folder (redirect if it does not exist in the root directory)

www.domain.com/folder1/a_folder

I know that I should use RewriteCond% {REQUEST_FILE}! -f, but I can’t understand what it is.

+6
source share
1 answer
RewriteEngine On RewriteBase / RewriteCond %{REQUEST_URI} !^/folder1/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule (.*) folder1/$1 [L,R] 
  • The first rewrite-cond ensures that you are not executing a loop (in case the file does not exist inside folder1, or
  • The second checks that the target is not a file
  • The third is not a folder either
  • Finally, rewrite the URL. Flag L means that this is the last rule applied (even if there are rules after it), R means redirection. You can also add the QSA flag if you want any query string parameters passed to the original to be sent to the new URL
+15
source

Source: https://habr.com/ru/post/918314/


All Articles