David
David

Reputation: 3323

htaccess - Remove www and selectively force https

Having a difficult time finding the combination to satisfy the following 3 conditions. What Rewrite rules and conditions will accomplish the conditions? (I've already been surprised by the rules not working.)

  1. www stripped from all requests
  2. https for all requests to primary
  3. http for all requests to subdomain (in subfolder of main site) subdomain.com

htaccess:

RewriteEngine On
RewriteBase /

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.primary\.mobi [NC,OR]
RewriteCond %{HTTP_HOST} ^primary\.mobi [NC,OR]
RewriteCond %{HTTP_HOST} !^(www\.)?subdomain\.com [NC]
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

The above do not strip www and send www.subdomain to https.

Explanations welcomed. Trying to understand the apache mod_rewrite manual page and have tried several methods without success.

Upvotes: 1

Views: 1564

Answers (1)

Olaf Dietsche
Olaf Dietsche

Reputation: 74018

You can capture the domain and use it in your RewriteRule. HTTP_REQUEST is not available in the substitution part, but only in RewriteCond directives.

I'm not sure, but you can try to split this into two .htaccess files. This one goes into the main directory

RewriteEngine On

# remove www. from HTTPS requests
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(primary\.mobi)$ [NC]
RewriteRule .* https://%1/$0 [R,L]

# redirect HTTP requests to HTTPS
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(primary\.mobi)$ [NC]
RewriteRule .* https://%1/$0 [R,L]

and this is for the .htaccess in the subdomain folder

RewriteEngine On

# remove www. from HTTP requests
RewriteCond %{HTTP_HOST} ^www\.(subdomain\.com)$ [NC]
RewriteRule .* http://%1/$0 [R,L]

# redirect HTTPS requests to HTTP
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^(?:www\.)?(subdomain\.com)$ [NC]
RewriteRule .* http://%1/$0 [R,L]

Test your rules without 301, because the browser caches 301 results and makes testing much harder. Add R=301 not until you're satisfied with the rules.

In Canonical Hostnames are some alternatives described, especially the first one, using virtual hosts, looks promising

<VirtualHost *:80>
    ServerName www.primary.mobi
    Redirect / https://primary.mobi/
</VirtualHost>

<VirtualHost *:80>
    ServerName primary.mobi
</VirtualHost>

<VirtualHost *:80>
    ServerName www.subdomain.com
    Redirect / http://subdomain.com/
</VirtualHost>

<VirtualHost *:80>
    ServerName subdomain.com
</VirtualHost>

I don't know, if this is feasible for you, but you might try.

Upvotes: 1

Related Questions