EIP
EIP

Reputation: 31

How to redirect everything except root and some folders in htaccess

I am looking for .htaccess code that will redirect all traffic at mydomain.com to example.com/folder1 except the root of example.com and folder2, folder3 and folder4. Summery: Url to redirect - all files and folders at example.com Redirect to - to example.com/folder1 Exception - root, folder2,folder3,folder4

RewriteEngine on 
RewriteBase / 
RewriteCond %{HTTP_HOST} ^example\.com$ 
RewriteCond %{REQUEST_URI} !^/folder1(/|$) 
RewriteCond %{REQUEST_URI} !^/folder2(/|$) 
RewriteCond %{REQUEST_URI} !^/folder3(/|$) 
RewriteCond %{REQUEST_URI} !^/folder4(/|$)

RewriteRule ^$ https://example.com/folder1 [L,R=301]

EDIT: Tried to use the above code to redirect but not sure if the code itself has issues because it doesn't seem to work as expected. What could be the problem? The Problem: I want the redirection to exclude home page, folder2, folder3, folder4 otherwise redirect everything to to folder1

Upvotes: 0

Views: 1077

Answers (1)

arkascha
arkascha

Reputation: 42984

Thanks to your comments and the additional information you gave the question becomes more clear now.

I suggest this rule set, it should get you closer to what you try to achieve, though it still might need some tweaking...

RewriteEngine on 
RewriteBase / 
RewriteCond %{HTTP_HOST} ^example\.com$ 
RewriteCond %{REQUEST_URI} !^/$
RewriteCond %{REQUEST_URI} !^/folder1/?
RewriteCond %{REQUEST_URI} !^/folder2/?
RewriteCond %{REQUEST_URI} !^/folder3/?
RewriteCond %{REQUEST_URI} !^/folder4/?
RewriteRule ^/?(.*)$ https://example.com/folder1/$1 [END,R=301]

This rule set will work likewise in the http servers host configuration or inside a dynamic configuration file (".htaccess" file). Obviously the rewriting module needs to be loaded inside the http server and in case you use a dynamic configuration file you need to take care that it's interpretation is enabled at all in the host configuration and that it is located in the host's DOCUMENT_ROOT folder.

And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those dynamic configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).

Upvotes: 1

Related Questions