0

I want to redirect:

https://example.com => https://www.example.com [not working]

http://example.com => https://www.example.com [not working]

www.example.com => https://www.example.com [working]

example.com => https://www.example.com [working]

.htaccess

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(.*)$  [NC]
RewriteRule (.*) https://www.example.com/$1 [R=301,L]

Virtualhost

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/test/public_html
    ErrorLog /var/www/test/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
<VirtualHost _default_:443>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/test/public_html
    ErrorLog /var/www/test/error.log
    SSLEngine on
    SSLCertificateKeyFile /etc/apache2/ssl/test.key
    SSLCertificateFile /etc/apache2/ssl/test.crt
</VirtualHost>
Community
  • 1
  • 1
RNK
  • 5,582
  • 11
  • 65
  • 133
  • Possible duplicate of [htaccess redirect to https://www](https://stackoverflow.com/questions/13977851/htaccess-redirect-to-https-www) – Sean Bright Jul 09 '19 at 18:49
  • 1
    @anubhava: I am using same documentroot in virtualhost settings. Please see updated question. – RNK Jul 09 '19 at 18:52
  • @SeanBright: I tried that solution as well. First it's redirecting to www and then again coming back to non-www and in this case getting `DNS_PROBE_FINISHED_NXDOMAIN` error. – RNK Jul 09 '19 at 18:55
  • What are you trying to achieve with `RewriteCond %{HTTP_HOST} ^(.*)$ [NC]`? https must be off OR the host doesn't start with www AND it has to contain any character? – Capsule Jul 10 '19 at 03:06
  • `First it's redirecting to www and then again coming back to non-www`: That's not happening in rule shown above. Do you have any other code/rule that is causing this? – anubhava Jul 10 '19 at 07:37
  • Also, you shouldn't use .htaccess at all if you have access to and can modify .conf files – Dusan Bajic Jul 10 '19 at 07:52

1 Answers1

0

I worked by this .htaccess config:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RNK
  • 5,582
  • 11
  • 65
  • 133