• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 289
  • Last Modified:

Creating sub-domains with PHP - is .htaccess the best way?

I've got a need to create sub-domains automatically in code as part of a project that i'm working on.  Having surfed around the web its seems one of those things that different people have got different views on.

Can anybody suggest the best option?  My thought was to set up a section in the .htaccess file, so that anything.domainname.tld gets redirected to domainname.tld/anything.  Would that work? Is it secure and is it the most efficent way of doing things?  

Programmically we are using php and a bit of python, if anyone can suggest other ways? Are there any code frameworks for php that provide an easier or better way of working where sub-domins are concerned?
0
lynxIT
Asked:
lynxIT
  • 2
1 Solution
 
trencH87Commented:
I would have used .htaccess as it is reliable. Im not sure if it is even possible with PHP, unless you edit your apache configuration with the php-script. Thats not safe, so stick with .htaccess.

I'll give you an example using htaccess. Not testet, so let me know if it throws any warnings.
# Turn engine on
RewriteEngine On

# Disable Multiviews as you don't need it.
Options -MultiViews

# The main conditions
RewriteCond %{REQUEST_URI}!^/
RewriteCond %{HTTP_HOST}!^www\.domain\.com [NC]
RewriteCond %{HTTP_HOST} ^([^.]+)\.domain\.com
RewriteRule (.*) /%1/$1 [L]

Open in new window

0
 
p_nutsCommented:
what server type.. most Apache servers automatically treat a subfolder under the root as a subdomain.
0
 
lynxITAuthor Commented:
@trencH87,
Thanks for that.  Quick question (I know the basics of how RewriteCond works) but what are Multiviews?

There are a couple of sub-domains that we have set up in the apache configuration, i.e. admin.domainname.com etc... how would this htaccess rewrite affect those?

I'll try it out and come back to you!

@P-nuts:
We're running CentosOS
0
 
trencH87Commented:
You can read more about the issues with MultiViews here: http://www.gerd-riesselmann.net/archives/2005/04/beware-of-apaches-multiviews

If the rewrite failes your already added subdomains, just exclude them in .htaccess.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now