Redirect all http requests (including subdomains) to https

Viewed 62

I have already tried different solutions from other threads but somehow none is working. So I have a domain called my-domain.com and I want that all http requests to http://my-domain.com or http:///*.my-domain.com are redirected to the corresponding https page. In the folder /etc/apache2/sites-enabled/ I have a configuration file which looks like this:

<VirtualHost *:80>
   ServerName my-domain.com
   ServerAlias *.my-domain.com

   RewriteEngine On
   RewriteCond %{HTTP_HOST} ^(.+)\.my-domain\.com$
   RewriteRule ^(.*)$ https://%1.my-domain.com/$1 [R=302,L]
</VirtualHost>

But still there are no redirects. All requests are failing because of a timeout. Is there something I am missing?

1 Answers

In your RewriteRule, the %1 is not doing what you think it will be doing.

# bad
RewriteRule ^(.*)$ https://%1.my-domain.com/$1 [R=302,L]

Try this:

# good
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

What we are doing here is taking ANY request that is NOT HTTPS, and rewriting it. We don't care about looking at the %{HTTP_HOST}, nor the %{REQUEST_URI}, because we will just use them blindly.

This is a "blind forward" to HTTPS. I don't care what you asked for, but since you did it over HTTP, you will have to do it over HTTPS.

At that point, it becomes a different rule to redirect further.

Additionally, 302 is a temporary redirect. You may wish to consider a 301, for a permanent redirect across ports.

Related