skip to Main Content

I’m new to editing htaccess files. What I want to do is:
rewrite/redirect specific subdomains eg subdomain1, subdomain2, etc from:

https://www.subdomain.example.com
http://www.subdomain.example.com
http://subdomain.example.com

To:

https://subdomain.example.com

I’ve pieced the below code together from other questions, but it doesn’t seem to be working.
Can anyone explain what I’m doing wrong and help me fix the code.

RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteCond %{SERVER_PORT} ^80$
RewriteCond %{HTTP_HOST} ^subdomain.example.com$ [NC]
RewriteRule .? https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

2

Answers


  1. You can use the following :

    RewriteEngine on
    
    RewriteCond %{HTTPS} off [OR]
    RewriteCond %{HTTP_HOST} ^www.
    RewriteCond %{HTTP_HOST} ^(?:www.)?(.+) [NC]
    RewriteRule ^ https://%1%{REQUEST_URI} [R,L]
    

    This will redirect all subdomains from http://www to https:// .

    For the subdomain.example.com you can use the following :

    RewriteEngine on
    
    RewriteCond %{HTTPS} off 
    RewriteCond %{HTTP_HOST} ^subdomain.example.com [NC]
     RewriteRule ^ https://subdomain.example.com%{REQUEST_URI} [R,L]
    
    Login or Signup to reply.
  2. To canonicalise ("redirect") only the specific subdomain

    https://www.subdomain.example.com
    http://www.subdomain.example.com
    http://subdomain.example.com
    

    To:

    https://subdomain.example.com
    

    You would need to do it something like this near the top of your .htaccess file:

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

    The 3rd condition ensures that it only applies to the specific subdomain.

    To make this apply to several subdomains (assuming the no-www is canonical for all subdomains) then you could modify just the 3rd condition to identify the subdomains that it should apply to. For example:

    RewriteCond %{HTTP_HOST} ^(?:www.)?((?:subdomain1|subdomain2|subdomain3).example.com) [NC]
    

    Test with a 302 (temporary) redirect to avoid potential caching issues. You will need to clear your browser cache before testing.


    RewriteCond %{HTTPS} !on
    RewriteCond %{SERVER_PORT} ^80$
    RewriteCond %{HTTP_HOST} ^subdomain.example.com$ [NC]
    RewriteRule .? https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    

    This is along the right lines, but it fails to target HTTPS or the www sub-subdomain. Also, checking %{HTTPS} !on and %{SERVER_PORT} ^80$ are really the same thing.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search