Let’s say I have a website that is available over HTTPS, e.g. https://example.com/foo
. Consider the following .htaccess
:
RewriteBase /
RewriteEngine On
RewriteRule ^foo$ bar [R=301,L]
Now, when I visit https://example.com/foo
, it redirects to http://example.com/bar
, over HTTP instead of HTTPS.
How can I make it go to HTTPS other than using the full scheme + host for every RewriteRule
with the R
flag? That is, this would do what I’m after:
RewriteBase /
RewriteEngine On
RewriteRule ^foo$ https://example.com/bar [R=301,L]
However, my .htaccess
file contains many such RewriteRule
s, and it feels like there should be a way to tell Apache/mod_rewrite “rewrite to https://
by default”. What I’m really looking for is a directive to tell Apache the site is using HTTPS, similar to how one can declare the host name through ServerName foo.ext
. Is that possible?
I guess this is a similar question on Stack Overflow: How to convince Apache of the original client protocol
ServerName
accepts a scheme as well, e.g.ServerName https://example.com
. Changing this in the configuration and restarting Apache did the trick.From the documentation:
This is a way to do it:
Put this into your httpd.conf, or before all your virtual host, and it will be applied to all requests starting with example.com (www.example.com will not be redirected)
To apply the rule to all domains, you can remove the line
RewriteCond %{HTTP_HOST} ^example.com
For information, you should avoid .htaccess usage if possible, to prevent useless hard disk access.
Is there any reason you are not using the plain Rewrite directive?
For sub domains, you can do