Using Apache Mod Rewrite to redirect from HTTP to HTTPS and from a different TLD

If there is a single domain and you want to remove www and force https so the final domain will be in the format:

https://domain.com


In .htaccess:

RewriteCond %{HTTPS} off

RewriteRule ^(.*)$ https://domain.com%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]

RewriteRule ^ https://domain.com%{REQUEST_URI} [L,R=301]

 

If the domain has a secondary top level domain such as .co.uk, you will need to ensure that secondary domain has a valid ssl cert if you want to redirect from that.


Use the following rules to also handle redirects from a second TLD to the main TLD:

RewriteCond %{HTTP_HOST} ^domain.co.uk

RewriteRule ^(.*)$ https://domain.com/$1 [L,R=301]

RewriteCond %{HTTPS} off

RewriteRule ^(.*)$ https://domain.com%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]

RewriteRule ^ https://domain.com%{REQUEST_URI} [L,R=301]

 

You will need to test all  the rules with the following urls which iterates through all permutations  (The following include some Drupal specific URIs for good measure too, and also assumes you have an about page).  All the requests should resolve to https://domain.com/uri

  1. https://domain.com/
  2. https://www.domain.com/
  3. https://domain.com/about
  4. https://www.domain.com/about
  5. https://domain.com/user/login
  6. https://www.domain.com/user/login
  7. https://domain.co.uk/
  8. https://www.domain.co.uk/
  9. https://domain.co.uk/about
  10. https://www.domain.co.uk/about
  11. https://domain.co.uk/user/login
  12. https://www.domain.co.uk/user/login
  13. http://domain.com/
  14. http://www.domain.com/
  15. http://domain.com/about
  16. http://www.domain.com/about
  17. http://domain.com/user/login
  18. http://www.domain.com/user/login
  19. http://domain.co.uk/
  20. http://www.domain.co.uk/
  21. http://domain.co.uk/about
  22. http://www.domain.co.uk/about
  23. http://domain.co.uk/user/login
  24. http://www.domain.co.uk/user/login


Comments

Popular posts from this blog

Rant: Don't name your mobile app with a pronoun prefix

Web 3.0: Component driven responsive design

Why you should use rem instead of px in webdesign