larrysanchez
larrysanchez

Reputation: 127

.htaccess redirect all subdomains to one directory, and preserve url

I have spend most of the afternoon googling this one and cant seem to get it to work at all (I am a bit rusty with htaccess!)

Basically I have a site, and every user registered has a subdomain (e.g. userA.example.com, userB.example.com)

I have been using a php script to register these subdomains, but now with over 500(!) subdomains, I am moving to a new server and thought I could possibly implement a new system.

I would basically like any subdomain appended to the domain to point to a single folder and keep the original url in the browser's address bar, so that I don't have to use server resources to register a new subdomain for every user!

I have already setup the wildcard DNS required for this.

I am using the following code to perform the redirect, but the address still changes:

RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.XXXX\.com$ [NC]
RewriteCond %{HTTP_HOST} ^([^.]+)\.XXXX\.com$ [NC]
RewriteCond %{SERVER_PORT} =80
RewriteRule ^(.*)$ http://XXXX.com/frontend/ [L,NC]

This does redirect absolutely fine, but I cannot figure out a way to preserve the original URL with subdomain.

Thanks for your help

Upvotes: 2

Views: 2001

Answers (2)

David Spector
David Spector

Reputation: 1671

I think a simpler method of handling any complex redirection is to use PHP. In the server config file or an .htaccess file, use the FallbackResource directive to send all URL requests to a single PHP file. In that file, use $_SERVER['HTTP_HOST'] to get the hostname and $_SERVER['REQUEST_URI'] to get the original URI. Then you can use

header('Location: https://subdomain.example.com/');

to redirect to any calculated URL you wish.

Upvotes: 0

anubhava
anubhava

Reputation: 784898

You need to first enable mod_proxy via your Apache config otherwise URL will change since you're changing domain name here.

Once mod_proxy is enabled try this rule:

RewriteEngine on

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^([^.]+)\.XXXX\.com$ [NC]
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ http://XXXX.com/frontend/ [L,NC,P]

Upvotes: 2

Related Questions