This is the code I used to setup a subdomain on my webserver. Paste these lines into the .htaccess file at the root level of the web/public folder. It seemed that nothing I read online could satisfy my needs and I found mod_rewire to be very challenging to work with. My main problem was that I ended up creating a loop and didn’t know it.
Here are my requirements:
- When users visit http://subdomain.domain.tld, display files located at http://domain.tld/mydirectory/
- Do not show /mydirectory/ in the url.
- Allow for the possibility of a user prefixing the subdomain with www.
Steps
- Make sure your DNS settings are correct. If you host your own DNS, setup an A record * and point to your IP Address. [*.domain.tld A 1.2.3.4].
- Make sure your webserver is setup to handle wildcard subdomains.
- Test your DNS by performing a lookup of subdomain.domain.tld
- Test your webserver by visiting subdomain.domain.tld and you should see the same thing you would see at domain.tld.
- Add the following code to your .htaccess file
Code Summary
# Required for mod_rewrite to work
Options +FollowSymLinks# Users should not view my directory listing.
# Other sites are wrong that this is required.
Options -Indexes# Turn on mod_rewrite
RewriteEngine On# Set directory for rewrites to occur, based on htaccess location.
# Mine will occur at the root level.
RewriteBase /# Don’t mess with www.domain.tld
# Unnecessary in this rule because no regexp
# used in subdomain portion of the next condition.
# Left here because it is used in some of my other rules.
RewriteCond %{HTTP_HOST} !www.domain.tld$ [NC]# Select what to rewrite.
# Only process pages beginning with
# www.subdomain.domain.tld or subdomain.domain.tld.
# Stores anything after ‘subdomain.domain.tld’ as string variable $1
RewriteCond %{HTTP_HOST} ^(www.)?subdomain.domain.tld [NC]# Prevent a loop.
# Don’t process pages that already referencing correct directory.
RewriteCond %{REQUEST_URI} !mydirectory/ [NC]# This tells mod_rewrite to load files in mydirectory.
# $1 is the string variable stored from
RewriteRule (.*) mydirectory/$1 [L]
Just the code
Options +FollowSymLinks
Options -Indexes
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^(www.)?subdomain.domain.tld [NC]
RewriteCond %{REQUEST_URI} !mydirectory/ [NC]
RewriteRule (.*) mydirectory/$1 [L]