1

I want to redirect my urls via htaccess from a particular sub-folder to main domain.

One option is to use the following rule

RewriteRule ^subfolder/(pattern)$ http://%{HTTP_HOST}/$1 [R=301,L]

works fine for real domain

redirects correctly
http://example.com/subfolder/page
to
http://example.com/page

works incorrectly for localhost

redirects
http://localhost/exmple/subfolder/page
to
http://localhost/page
instead of 
http://localhost/exmple/page

modifying the rule as follows works for localhost but not for real domain

RewriteRule ^subfolder/(pattern)$ http://%{HTTP_HOST}/example/$1 [R=301,L]

I use localhost environment for development and testing before uploading the script to the host web server.

Please tell if this is possible to handle the above scenario in a generic way so that I don't need to maintain two copies of code/htaccess - one for local and one for real domain.

azb
  • 11
  • 3

1 Answers1

0

Finally, got solution to my own question. Here is how to redirect a url to a new one by replacing only the desired part of the input url - works both on localhost and real domain.

Get current directory path into a variable "BASE"

RewriteCond %{REQUEST_URI}::$1 ^(.*?/)(.*)::\2$
RewriteRule ^(.*)$ - [E=BASE:%1]

Capture the desired portion of the url and redirect there

RewriteRule ^subfolder/(pattern)$ %{ENV:BASE}$1 [R=301,L]

First part is to get the current directory's relative path into a variable. More detail here.

Then capture the desired url portion here "(pattern)" and redirect without any protocol or domain name.

The actual protocol, domain name and query strings will be maintained. So works well for both localhost and real domain.

azb
  • 11
  • 3