7

I need to rewrite a subdomain to a subdirectory using .htaccess but keep the subdomain in the url like this:

Visited url in browser: sub1.domain.com

Served url: sub.domain.com/sub1/

I tried the following

RewriteCond %{HTTP_HOST} ^subdomain.domain.com RewriteRule ^(.*)$ http://subdomain.domain.com/subdomain/$1 [L,NC,QSA] 

but this leads to an endless loop. I know that it would be easier to do this by php but is there any solution for this with using .htaccess?

1 Answer 1

19

You can use this rule in document root:

RewriteCond %{HTTP_HOST} ^subdomain\.domain\.com$ [NC] RewriteRule ^((?!sub1/).*)$ /sub1/$1 [L,NC] 

Explanation:

  • NC: Ignore case
  • L: Last rule
  • RewriteCond %{HTTP_HOST} line makes sure that rule only executes for subdomain
  • (?!sub1/) is negative lookahead expression that means of request is not starting with /sub1/
  • RewriteRule ^((?!sub1/).*)$ /sub1/$1 [L,NC] rewrites current path to /sub1/<uri>

References:

Sign up to request clarification or add additional context in comments.

11 Comments

@MDeuerlein,That means you didn't setup subdomains correctly on your server.
It was indeed past of the op's coffee in the question and in any case the are just place holders as op didn't reveal actual domain name (justifiably). Please consider opening a different question if you are running into problems.
Finally...spent over an hour figuring out how to make a .htaccess which correctly handles domain and subdomains. This answer worked. Obviously you'll want to replace 'subdomain', 'domain', and 'sub1' with your data.
@bharal: I've added explanation and references in the answer. Spend some time reading manuals and ask a specific question if you have.
@anubhava I am truly grateful!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.