Search code examples
php.htaccesshttp-redirectwebserver

How to redirect any input to both https and www?


I need example.com be redirected to https://www.example.com.

My .htaccess file is in the root directory and configured like this:

RewriteEngine On
DirectoryIndex html/home5.html
RewriteRule ^\.htaccess$ - [F]
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

With this configuration, www.example.com, https://example.com and http://example.com are all redirected to https://www.example.com (www.example.com/other.html and so on work respectively) correctly.

But example.com gets redirected to https://www.example.com/http://www.example.com/ and obviously produces "The requested URL was not found on this server". Why does this happen? What do I need to change to make it work?

I also don´t understand why with my current configuration https://example.com the www is added correctly.


Solution

  • Got a well working .htacces i'm using for the same problem, with 2 steps :

    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]
    

    First, if the requested url got HTTPS "off", redirect to HTTPS and add the url request query after (saved in $1).

    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ https://www.%1/$1 [L]
    

    Then, special case for www. subdomain and https on, if matching "www" in the request, redirect to the same page with https on !

    EDIT : you don't even need the second condition in fact