Using .htaccess I am successfully redirecting a specific set of subfolders ( blog, dev, media, etc ) to subdomains.
Like so:
www.website.com/_subs/dev/foogets directed todev.website.com/foo
This has been achieved with the following fragments of code:
RewriteEngine on RewriteBase / RewriteCond %{HTTP_HOST} ^website.com$ RewriteRule ^(.*)$ http://www.website.com/$1 [R=301,L] RewriteCond %{HTTP_HOST} website.com RewriteCond %{REQUEST_URI} ^/_subs/blog/(.*)$ RewriteRule .* http://blog.website.com/%1 [R=301,L] RewriteCond %{HTTP_HOST} website.com RewriteCond %{REQUEST_URI} ^/_subs/dev/(.*)$ RewriteRule .* http://dev.website.com/%1 [R=301,L] RewriteCond %{HTTP_HOST} website.com RewriteCond %{REQUEST_URI} ^/_subs/media/(.*)$ RewriteRule .* http://media.website.com/%1 [R=301,L]
The question is:
How do I prevent access to the
/_subsfolder if a request ISN’T made to one of my specific subfolders?
I would like any requests being made to www.website.com/_subs/foo to simply be redirected to www.website.com
I have tried using a 301 redirect along with various other attempts to no avail 🙁
Any help would be greatly appreciated.
Cheers
Your rules are a lot more complicated than they need to be and I think that’s making the solution harder to see.
Here’s what I came up with:
The
RewriteConds limit the first two rules so that they only run onwebsite.comandwww.website.com. Presumably you might have a url likehttp://blog.website.com/_sub/this-rocksin the future that you don’t want redirected.Including both domains in the first rewrite means you will have one less 301 redirect, which should make a request to http://website.com/_sub/blog redirect directly to http://blog.website.com much faster. The L makes sure that nothing that matches this rule will get marked as forbidden.
The second rewrite returns 403 for anything starting with
/_subthat is not matched by the first rule. The/is inside the group so that this will match/_sub,/_sub/, and/_sub/.*. If the/were outside you would not be able to 403/_subwithout a separate rule.The last rewrite is the same as your very first rule – there is no need to put the L, though, as it’s already the last rule to process.