Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mod rewrite directory if file/folder not found

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

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

I need to redirect all the requests to www.domain.com that turn up to be a 404 error, to folder1. Like so:

www.domain.com/a_file.txt

If a_file.txt doesn't exist, look in folder1:

www.domain.com/folder1/a_file.txt

I want this to work the same for subdirectories, like so:

www.domain.com/a_folder (redirect if it doesn't exist in the root)

www.domain.com/folder1/a_folder

I know I should use RewriteCond %{REQUEST_FILE} !-f but I can't seem to figure it out.

like image 420
user1462610 Avatar asked Jun 18 '12 02:06

user1462610


People also ask

How does mod rewrite work?

mod_rewrite works through the rules one at a time, processing any rules that match the requested URL. If a rule rewrites the requested URL to a new URL, that new URL is then used from that point onward in the . htaccess file, and might be matched by another RewriteRule further down the file.

How do I enable rewrite mod?

Step 1 — Enabling mod_rewrite In order for Apache to understand rewrite rules, we first need to activate mod_rewrite . It's already installed, but it's disabled on a default Apache installation. Use the a2enmod command to enable the module: sudo a2enmod rewrite.

What is rewrite path?

RewritePath(String, Boolean) Rewrites the URL using the given path and a Boolean value that specifies whether the virtual path for server resources is modified. RewritePath(String) Rewrites the URL using the given path.


1 Answers

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 you do not loop (in case the file does not exist inside folder1 either
  • The second one checks that target is not a file
  • The third - that it is not a folder either
  • And, finally, rewrite the url. L flag means this is the last rule applied (even if there are rules after it), R means redirect. You can also add QSA flag if you want any query-string parameters passed to the original be sent to the new url
like image 84
poncha Avatar answered Sep 30 '22 13:09

poncha