For a website, I want to set up a redirection using .htaccess. My folder structure is something like
/
/folderA/
/folderB/
/index/
where folderA and B and index contain subfolders and files. Now, I want to rewrite all requests for the root /
and for all not existing folders and files to index
. It should be masked. It seems to me like an easy task but I cannot get it to work. So far, I tried
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) /index/$1 [L]
The redirection somehow works but it does not work when I call the root http://example.org/ directly. Is the root also seen as valid directory or excluded in the RewriteCond checks? Any ideas how to realize that?
CodePudding user response:
Yes, the root is also a directory. You will need to add another rule to rewrite the root only. For example:
RewriteRule ^$ /index/ [L]
And since the root is a directory, you might as well exclude this from the first rule. ie. Change (.*)
to (. )
.
HOWEVER, your existing rule will result in a rewrite-loop (500 error) if the URL you are rewriting to in /index/...
does not exist either*1. eg. If you request /foo
, it rewrites to /index/foo
and if /index/foo
does not exist then it rewrites to /index/index/foo
to /index/index/index/foo
etc.
You will need to add an additional condition (or use a negative lookahead) to prevent requests to /index/...
itself being rewritten.
(*1 Unless you have another .htaccess
file in the /index
subdirectory that contains mod_rewrite directives and you have not enabled mod_rewrite inheritance.)
For example:
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/index/
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (. ) /index/$1 [L]
RewriteRule ^$ /index/ [L]