1

For my local dev environment, I have just upgraded from MAMP to MAMP Pro so that I can easily create virtual hosts without getting too involved with configuration files. Server names will be formatted as: foldername.localhost

For my site's directory I want to create an htaccess rule to redirect from http://localhost/foldername to http://foldername.localhost, where "foldername" is a wildcard.

Is this possible?

1

Yes, this is possible:

RewriteEngine On
RewriteCond %{HTTP_HOST} =localhost
RewriteCond %{DOCUMENT_ROOT}/$1 -d
RewriteRule ^([^/]+)(.*) http://$1.localhost$2 [R=301,L]

This will redirect http://localhost/foldername/path/to/file to http://foldername.localhost/path/to/file (where /path/to/file is optional).

There are two parenthesised sub patterns for the "foldername" ($1) and "URL path" ($2).

The second RewriteCond directive checks to see whether the first part of the URL is a valid directory.

|improve this answer|||||
  • I have multiple sites in various folders hence the requirement for foldername to be a wildcard. Is the solution above such that I would need to create a rule for each site? – MrPaulDriver Nov 23 '13 at 16:48
  • It did. I've changed it to be more general. – MrWhite Nov 23 '13 at 16:58
  • I've updated (fixed) the code... the RewriteCond directive wasn't checking the local filesystem path. – MrWhite Nov 23 '13 at 17:25
  • I really appreciate your help with this, but so far your solution is not working for me. – MrPaulDriver Nov 23 '13 at 18:10
  • In what way is it not working? Is it redirecting anything? Is there anything else in your .htaccess file that it might be conflicting with? – MrWhite Nov 23 '13 at 18:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.