jasondeegan jasondeegan - 4 months ago 16
Apache Configuration Question

How can I write .htaccess rules for multiple domain circumstances

I have two main types of domains directed to my web server. The main traffic (example.com) I want to direct to https, but the rest of the traffic (i.e. profile1.net, profile2.net, etc.) I want to leave as http. For this reason, I can't use a catch-all SSL redirect type of rule. Additionally, I have more rules that redirect profile names and hide extensions and such, so I can't use the L directive after the RewriteRule

I would also like to direct all the main traffic to include the subdomain www.

I can't seem to put the two pieces together, the system seems to ignore one of the conditions. Please review:

Options +FollowSymLinks
RewriteEngine on

RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^/?$ "https://www.example.com/$1" [R=301]

RESULTS: Test cases 3 & 4 work. Test cases 1 & 2 show as http://

If I comment out the www. line in the conditional, the example.com works flawlessly:

Options +FollowSymLinks
RewriteEngine on

RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
#RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^/?$ "https://www.example.com/$1" [R=301]

RESULTS: Test cases 1, 3 & 4 work. Test case 2 shows as http://

Test cases:

  1. example.com -> https://www.example.com

  2. www.example.com ->

  3. https://example.com ->

  4. https://www.example.com ->

*These test cases do not apply for this example, but do in the overall *

  1. [any of the above]/signup.php ->

  2. profile.net -> profile.net

  3. www.profile.net -> www.profile.net

  4. https://profile.net -> THROWS

  5. https://www.profile.net -> THROWS SSL


Here is a single 301 redirect rule for all 4 cases:

RewriteEngine on

RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(example\.com)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]