Search code examples
.htaccesshttphttp-redirecthttpssubdomain

.htaccess general format of http redirect to https with all subdomains restriction


I see everywhere dozens of guides about how to do redirects from http to https but only few are general in terms of domain names + NONE of them try to avoid situation of "subdomain scaming". With "subdomain scaming" I mean when someone is trying to access www.fdasfsdafa.example.com on website www.example.com. I would expect that this will redirect into https://www.example.com. I need some general example with code variables for domain name. Why? Because I have multiple domain multisite! Many thanks for any help! I spent hours with googleing on this but there is not simply any usable example.

Here is my current code. It works great, but does not handle subdomains redirects to https main domain. Subdomains basically open http site = unsecured website.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]

RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
</IfModule>

Solution

  • You can use:

    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    
    # subdomains restriction -> https www.domain
    RewriteCond %{HTTP_HOST} !^(www\.)?[^.]+\.[^.]+$ [NC]
    RewriteCond %{HTTP_HOST} ^.+\.([^.]+\.[^.]+)$
    RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R=301]
    
    # http -> https www.domain
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]
    
    </IfModule>