Forum Moderators: phranque
I just registered today after having used many previous threads from this site as guidance for mod_rewrite.
However, none of the threads showed me exactly how to do what I wanted and I read the two-part mod_rewrite tutorial on this site to no avail. Thus, I come for helo directly...
I would like this:
http://sub.example.com/gallery/request.php
to become:
http://example.com/gallery/sub/request.php
Now, after having read a few threads here and going through the tutorial, I've come up with this:
RewriteCond %{HTTP_HOST} ^([^/]+).(.+)
RewriteCond %{REQUEST_URI} ^/gallery/(.*)
RewriteRule ([^.]+)(\.example.comt)(.*) gallery/$1/$3 [L,R,QSA]
Now, you all look and that and say, "Oh man, that's not gonna work..." :)
The part I'm missing is how to pull out the subdomain as a variable to be used in the URL. How does one do what I want to do?
Thanks in advance...
[edited by: jdMorgan at 11:39 pm (utc) on Nov. 23, 2005]
[edit reason] Example.com [/edit]
How does one do what I want to do?
Use %1 through %9 in the RewriteRule substitution to back-reference the matched contents of parenthesized sub-expressions in RewriteCond.
For use in .htaccess:
RewriteCond %{HTTP_HOST} !^www\.example\.com
RewriteCond %{HTTP_HOST} ^(www\.)?([^.]+)\.example\.com
RewriteRule ^gallery/request\.php$ /gallery/%1/request.php [L]
RewriteCond %{HTTP_HOST} !^www\.example\.com
RewriteCond %{HTTP_HOST} ^(www\.)?([^.]+)\.example\.com
RewriteRule ^/gallery/request\.php$ /gallery/%1/request.php [L]
An internal rewrite is used rather than an external redirect, so the user always sees the URL he entered, and does not see the /gallery/sub/ path. [R] should not be used in this case, and [QSA] is not needed, since you are not appending additional query string parameters.
Jim
So, if I wanted to match ALL subdomains, including www, I would do the following, right?
RewriteCond %{HTTP_HOST} ([^.]+)\.example\.com
RewriteRule ^gallery/request\.php$ /gallery/%1/request.php [L]
Thanks a lot for the help so far.
One more thing... forget the request.php part. Would this work for any call inside /gallery/?
RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.com
RewriteRule ^gallery/(.*)$ /gallery/%1/$1 [L]
If I understand correctly, this will take any text after the / and turn it into $1 which I can then pass forward to the scripts in the appropriate subdomain dir. Yes?
The easiest way to avoid this is to rewrite sub.example.com/lmn/abc.xyz to /lmn/s_sub/abc.xyz, and then test for the subdirectory prefix "s_" to avoid looping, using
RewriteCond %{REQUEST_URI} !^/lmn/s_.
Note that "s_" can reqally be anything -- as long as it is sufficiently unique to never appear in the subdomain name itself or in another subdirectory path.
Jim