3

I had a subdomain setup in cpanel before (sub.domain.com to redirect to domain.com/sub/) and suddenly today I noticed that it was rewriting the URL in the browser to www.domain.com/sub/ instead of just just leaving it as sub.domain.com. I wasn't sure what the problem was, but decided to delete my sub domain and recreate it in cpanel. Now I can only access it by going to www.sub.domain.com (sub.domain.com yields a server not found error).

EDIT: The problem seems to lie with the .htaccess file. After deleting it, things went back to normal. However now my new problem is how to configure the .htaccess file properly. I had tweaked it originally to try and accomplish the following:

I have three folders, live, staging, and dev:

1) Requests for domain.com or www.domain.com are directed to domain.com/live (and the url the user sees is always rewritten as www.domain.com).

2) Requests for staging.domain.com and dev.domain.com or directed to domain.com/staging and domain.com/dev, respectively, and the user sees staging.domain.com or dev.domain.com in the browser.

3) Any subdomains in general are not rewritten by the browser when I add it in cpanel.

My current .htaccess file accomplishes number 1 just fine, but rewrites staging.domain.com to www.domain.com/staging and so forth.

RewriteCond %{HTTP_HOST} !^www\.domain\.com$
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,L]
RewriteRule ^$ /index.html

RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !\..+$
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://www.domain.com/$1/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/live/
RewriteRule ^(.*)$ /live/$1
Choy
  • 169
  • 2
  • 9

1 Answers1

0

I tweaked the logic of my original code and seem to have a viable working solution. Every test I've done has been successful, if anyone sees any flaws in the code, or how it might be optimized to fit the conditions posed in the original question, please chime in. I have little experience working with rewrites. Thanks.

Working Code:

# REDIRECTS
#
# Add www in front of all URLs except subdomains
#
RewriteCond %{HTTP_HOST} ^domain\.com$
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,L]
RewriteRule ^$ /index.html
#
# Add forward slash at end of www URLs
#
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.domain\.com$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !\..+$
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://www.domain.com/$1/ [R=301,L]
#
# Forward requests to live folder
#
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/live/
RewriteRule ^(.*)$ /live/$1

*Note: I'm not sure why the last part of the code does not redirect subdomain URLs to a live folder. It works the way I want it to, just not sure why ^_^;

Choy
  • 169
  • 2
  • 9