I’m attempting to use mod_rewrite to redirect requests to 123.example.com/456/file.html to example.com/123/456/file.html. The rewrite is necessary because new directories may be created on the fly. I’ve tried to reason through it but can’t seem to come to a working solution.
First, if I use the below rewrite rules I get a 404 for everything because it runs the second rule successfully, does internal redirection, proceeds to run the rules again and the first rule matches because it’s looking for 123/123/456/file.html, causing a 404.
RewriteCond %{HTTP_HOST} ^(\d+)\.
RewriteCond %{DOCUMENT_ROOT}/%1/$1 !-d
RewriteCond %{DOCUMENT_ROOT}/%1/$1 !-f
RewriteRule (.*) - [R=404,L]
RewriteCond %{HTTP_HOST} ^(\d+)\.
RewriteCond %{DOCUMENT_ROOT}/%1/$1 -d [OR]
RewriteCond %{DOCUMENT_ROOT}/%1/$1 -f
RewriteRule (.*) /%1/$1 [L]
If I move the 404 to be last, I get the following:
RewriteCond %{HTTP_HOST} ^(\d+)\.
RewriteCond %{DOCUMENT_ROOT}/%1/$1 -d [OR]
RewriteCond %{DOCUMENT_ROOT}/%1/$1 -f
RewriteRule (.*) /%1/$1 [L]
RewriteCond %{DOCUMENT_ROOT}/$1 !-d
RewriteCond %{DOCUMENT_ROOT}/$1 !-f
RewriteRule ^(.*)$ - [R=404,L]
It almost works as I need it, but doesn’t 404 when you enter 123.example.com/123/, even though it should be invalid. Since the path wasn’t rewritten by the first rule, $1 evaluates to 123/ instead of the invalid path 123/123/, which makes the request succeed without any rewrite rules running.
I feel like I’m very close to getting this to work. Any help is appreciated.
Add the following RewriteCond before your first set of Rules as below to prevent internal redirection