views:

150

answers:

1

Hi,

I'm trying to get a subdomain rewrite working using an Apache htaccess file and need some help please.

I am trying to get requests for http://xyz.example.com internally handled as if the user had requested http://example.com/xyz so the user does not see this URL in their address bar - they see the subdomain version.

This is slightly complicated by the fact that anything following this also needs to be passed too, for example if the user requests http://xyz.example.com/test/word/?x=123 then this needs to be handled by the server as if they had visited http://example.com/xyz/test/word/?x=123.

The site is running on the Code Igniter framework, which had its own htaccess rules too, but I guess this rewrite would be done first before those kick in.

Any help would be greatly appreciated!

A: 

The following mod_rewrite rule set should perform the rewriting you need:

RewriteCond $0 !^(index\.php/)?xyz
RewriteCond %{HTTP_HOST} ^xyz\.
RewriteRule ^.*$ /xyz/$0 [L]

The query string gets passed along automatically, since we haven't changed it in the rewrite.

For CodeIgnitor to pick this change up though, you'll need to be using PATH_INFO as the source of the routing information. Your $config['uri_protocol'] needs to be set to PATH_INFO or AUTO for this to be the case, and your CodeIgnitor RewriteRule should look something like the following:

RewriteRule ^.*$ /index.php/$0

If you run into trouble trying to use PATH_INFO, you'll need to find a way to get CodeIgnitor to parse $_SERVER['REDIRECT_URL'] (and add the L flag to the first RewriteRule up there). Hopefully this shouldn't be necessary, but if you can't get it to work otherwise I'll look into how you might do that.

Tim Stone
Hi Tim, Thanks for looking into this. However strangely I get a 403 forbidden error, despite having PATH_INFO set. In the error_log it says "File name too long: Cannot map GET / HTTP/1.1 to file". The CI RewriteRule did look slightly different, but even after changing that to yours it still wouldn't work. The good news is that in the meantime one of my colleagues has also been experimenting with it - we've both been trying to get it to work! - and has now managed to make it work using RewriteCond %{HTTP_HOST} ^xyz\.example\.com$ [NC] RewriteRule ^(.*)$ http://example.com/xyz/$1 [P] Thanks
GSA
@GSA - Ah yeah, that's because I failed to consider what happens after the CodeIgnitor rewrite. For completeness, I've updated the answer to fix that scenario. Your colleague's solution of using the `P` flag is fine too; I had just avoided suggesting that because it has the overhead of creating a brand new request as part of the proxy. Admittedly that's a non-issue if your server isn't under strain though.
Tim Stone