Reputation: 419
I would like to htaccess-redirect all visitors from a subfolder of a domain to the same subfolder in another domain. That should apply to all subfolders and files - but only for the folder "folder"
For example:
foo.com/folder -> bar.com/folder
and with sub-structure
foo.com/folder/subfolder/file.php -> bar.com/folder/subfolder/file.php
All the posts I found were only concerning (sub)folders and not the domains.
Thanks!
Update: Thanks to the contributers - of course I tried to search, but Drupal blocked the redirects, so I didn't think the answers I found worked. Thanks anyways for the correct answer!
Upvotes: 0
Views: 27
Reputation: 42935
This should roughly be what you are looking for:
RewriteEngine on
RewriteRule ^/?(.*)$ https://example.com/$1 [END,QSA]
That rule will work likewise in the http servers host configuration and in dynamic configuration files (".htaccess").
In case you receive an "internal server error (http status 500)" with this chances are that you operate a very old version of the apache http server. In that case will find a hint on this in the http servers error log files. You need to replace the [END]
flag with the [L]
flag in that case.
In case you operate both domains as virtual hosts on a single http server you need to take care not to create an endless rewriting loop. In that case add a condition to prevent such loop:
RewriteEngine on
RewriteCond %{HTTP_HOST} !^example\.com$
RewriteRule ^/?(.*)$ https://example.com/$1 [END,QSA]
A general hint: you should always prefer to place such rules inside the http servers (virtual) host configuration instead of using dynamic configuration files (.htaccess
style files). Those files are notoriously error prone, hard to debug and they really slow down the server. They are only provided as a last option for situations where you do not have control over the host configuration (read: really cheap hosting service providers) or if you have an application that relies on writing its own rewrite rules (which is an obvious security nightmare).
UPDATE:
In a comment below you mention that you want to apply such redirection only to a specific subfolder in the request path. To do that you just have to modify the matching pattern:
RewriteEngine on
RewriteCond %{HTTP_HOST} !^example\.com$
RewriteRule ^/?folder/(.*)$ https://example.com/folder/$1 [END,QSA]
An alternative would be that:
RewriteEngine on
RewriteCond %{HTTP_HOST} !^example\.com$
RewriteRule ^/?(folder/.*)$ https://example.com/$1 [END,QSA]
Upvotes: 1