1

I have a project im working on, when a user tries to accesses x.website.com it would show results for a specific state, how would I go about this without making 52 subdomains manually?

Is there a way to do it with htaccess? but this should also work if, state.website.com/search.php is accessed, it would show all the results for state X so I need it to be a constant variable.

Or is there a better way? Could anyone help?

Thank you

Saulius Antanavicius
  • 1,371
  • 6
  • 25
  • 55

1 Answers1

3

You need to define a wildcard DNS record as *.example.com. Any subdomain accessed which doesn't have a real DNS record defined will be sent to the wildcard record.

Check with your domain registrar to see if you are permitted to create a wildcard record.

In your .htaccess file, you can map the subdomains like so:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(.+)\.example\.com$ [NC]
# The state is captured as %1
RewriteRule . /index.php?state=%1 [L,QSA]

# More generically - pass the state to any request
# I think this will work without going to a redirect loop
RewriteRule ^(.+)$ $1?state=%1 [L,QSA]

Inside index.php once you have retrieved the state from the querystring, you can store it in $_SESSION and use that as a search filter.

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • so would I have to have both of them done? DNS wild card and htaccess? Also am I wrong in thinking that this wouldnt work for lets say state.website.com/search.php ? as it would try to pass to index.php? – Saulius Antanavicius Aug 03 '11 at 02:16
  • You will need both the wildcard DNS record and .htaccess. However, you can just store the querystring value of `?state=` in `$_SESSION` with PHP and retrieve it for searches. – Michael Berkowski Aug 03 '11 at 03:00