I've seen everything from basing requests off server ports, using server name requests rather than entering in an actual domain, to editing my apache configuration file and disregarding htaccess completely.
Apart from there being "many ways to skin a cat" (because Apache config files are a very flexible/complex beast), the method that is "best" for you can be dependent on many other factors:
- Your server configuration. (eg. is
UseCanonicalName On
set?)
- Do you have access to the main server config or
<VirtualHost>
container? Or are you restricted to .htaccess
(eg. a shared server environment).
- Are you running your site off non-standard ports?
- Are you hosting multiple domains off the same vHost?
- Do you need a generic solution that doesn't explicitly include the hostname? Do you want a solution that can be copy/pasted between hosts? Although a "generic" solution isn't necessarily the best (or "safest") solution for any one host. (Explicitly hardcoding the hostname is often the "safest" solution when anyone is suggesting a method to use, as we don't know how your server is configured.)
- Are you planning on implementing HSTS? (If so, then you probably don't want to canonicalise the hostname at the time you redirect from HTTP to HTTPS.)
- How is the security certificate managed for your site? eg. Is the SSL cert installed directly on your application server or are you using an SSL proxy (eg. Cloudflare)? If you are behind an SSL proxy then the
HTTPS
and SERVER_PORT
server variables are probably no good to you. (Some hosts set alternative environment variables to help - but this is server specific.)
So what is the most elegant way to make this code force https?
Well, "elegance" can be subjective.
If you have access to the server config then you shouldn't really be doing this in .htaccess
. Instead, you should be using a simple mod_alias Redirect
in the relevant <VirtualHost>
container - as @PatrickMevzek suggests. This is both "simpler", "safer" and more efficient.
If you later want to implement HSTS (and particularly to get on the HSTS preload list) then this really does become easier to implement in the main server config. To implement this in .htaccess
requires additional complexity.
RewriteCond %{HTTPS} off
RewriteRule (.*) https://www.example.com/$1 [R=301,L]
Otherwise, if you only have access to .htaccess
then there is really nothing "wrong" with the directive you are suggesting - providing it works. But bear in mind that this won't necessarily work on every server, or be the correct solution in every scenario, and could potentially be (inadvertently) overridden if you have additional .htaccess
files in subdirectories.
RewriteRule ^$ /index.html [L]
Aside: This rule should be unnecessary providing you have the DirectoryIndex
set correctly? (Unless maybe you have something "special" going on?)