How to do a http redirect to https

11

Well there must already be a question very similar to this in stackoverflow.

But before marking as a duplicate, I have an expecification that I did not find any "equal" question that I'm going to do.

Well I intend it is as follows:

I have several domains whose virtualhost point to the same physical path /www/site/public_html .

However the domain: example.com, I bought ssl and it has https.

What I wanted to do was an htacess file that would make me redirect the http: // and www to https to my example.com domain.

However, I do not want other domains to be affected, that is, I do not want other domains to have https.

In short:

Make 1 condition that if the user comes from http: // example.com or www.example.com automatically redirect to https: // example.com however, if it comes from another domain does nothing.

How could this be possible?

<VirtualHost *:80>
    ServerName www.foo.bar
    Redirect / https://www.foo.bar/
</VirtualHost>

<VirtualHost *:443>
    ServerName www.foo.bar
    # ... Configuração SSL
</VirtualHost>

Thank you.

    
asked by anonymous 23.07.2016 / 06:28

2 answers

11

RewriteRule is no longer recommended per the Apache documentation .

For the same effect, the recommended method is redirect :

<VirtualHost *:80>
    ServerName www.site.com
    Redirect / https://www.example.com/
</VirtualHost>

You will then also need to configure the service that will offer HTTPS:

<VirtualHost *:443>
    ServerName www.example.com
    SSLEngine On
    SSLCertificateFile /etc/ssl/localcerts/www.example.com.crt
    SSLCertificateKeyFile /etc/ssl/localcerts/www.example.com.key
    SSLCACertificateFile /etc/ssl/localcerts/ca.pem  # Se estiver utilizando um certificado auto-emitido, omita essa linha
</VirtualHost>

Source.

    
25.07.2016 / 14:55
10

This is a very simple alternative:

RewriteEngine On 
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com$ [NC]
RewriteRule ^.*$ https://www.domain.com%{REQUEST_URI} [R,L]

If you want everything to go to the% w / o of%, change the last line to

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

If you prefer to keep www as typed, change the last line to

RewriteRule ^.*$ https://%1domain.com%{REQUEST_URI} [R,L]

Remembering that if you put the certificate on the same IP of the sites WITHOUT a certificate, and someone trying to access www will give error anyway, because SSL negotiation comes before Apache processes the page.

And that's why SSL-enabled site puts itself in exclusive IP (or if you spend money on certificates for multiple domains).

    
25.07.2016 / 14:52