drew

Words on your display.

Archive for the ‘subdomain’ tag

Redirect all but used subdomains to primary domain using mod_rewrite and CodeIgniter

with 3 comments

I was recently playing with mod_rewrite and wanting a couple of subdomains to act as subdomains, but all others to redirect back to my site without the leading “www”. For example:

www.example.com => example.com
bad.example.com => example.com
api.example.com => api.example.com

Not being a regular expression or mod_rewrite expert (or any resemblance of such), this was a bit of a challenge. But I did it with the help of a mod_rewrite and regular expression cheat sheet, as well as the excellent Apache URL Rewriting Guide.

So here it is for anyone else that could benefit. Just replace the bold parts with your own subdomains (and example with your domain).

Redirect without leading www:
# Redirect deleting leading www to root domain if no specified subdomain is used
RewriteCond %{HTTP_HOST} !^(subdomain1|subdomain2)\.example\.com$ [NC]
RewriteCond %{HTTP_HOST} !^example\.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]

Redirect with leading www:
# Redirect adding leading www to root domain if no subdomain is specified
RewriteCond %{HTTP_HOST} !^(subdomain1|subdomain2|www)\.example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

If you’re using CodeIgniter and mod_rewrite for pretty URLs, you’ll need to be sure to add these subdomains to the list of directories that can be accessed directly.
# CodeIgniter writing
RewriteCond $1 !^(index\.php|images|robots\.txt|css|user_files|subdomain1|subdomain2)
RewriteRule ^(.*)$ /index.php/$1 [L]

Written by Drew

September 21st, 2008 at 2:10 pm