Niahm
Niahm

Reputation: 396

Apache VirtualHost: strip www. and force https

I am working on a site that only owns an SSL cert for monsite.fr. I am trying to remove the www. and redirect to https://monsite.fr. the redirection doesn't work if the user type www.monsite.fr, he WILL NOT be redirected to https://monsite.fr but to https://www.monsite.fr and get certification error NET::ERR_CERT_COMMON_NAME_INVALID.

This is the content of mysite.conf file:

<IfVersion < 2.3 >
  NameVirtualHost *:80
  NameVirtualHost *:443
</IfVersion>

<VirtualHost *:80>
  ServerName monsite.fr
  Redirect / https://monsite.fr/

  #RewriteEngine On
  #RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
  #RewriteRule ^(.*)$ https://%1$1 [R=permanent,L]
</VirtualHost>

<VirtualHost *:80>
  ServerName www.monsite.fr
  Redirect / https://monsite.fr/
</VirtualHost>

<VirtualHost *:443>
  ServerName monsite.fr
  ServerAlias www.monsite.fr

  #RewriteEngine On
  #RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
  #RewriteRule ^(.*)$ https://%1$1 [R=permanent,L]

  RewriteEngine On
  RewriteCond %{HTTPS} =on
  RewriteCond %{HTTP_HOST} ^www\.
  RewriteRule ^(.*)$ https://monsite.fr/$1 [R,QSA,L]

  DocumentRoot "/opt/monsite.fr/htdocs"
</VirtualHost>

Is there a solution to redirect www.monsite.fr to https://monsite.fr ?

Upvotes: 0

Views: 244

Answers (1)

Nidhi
Nidhi

Reputation: 888

Modify your vhost configuration as follows:

  <VirtualHost *:80>
      ServerName www.monsite.fr
      ServerAlias monsite.fr
      RedirectMatch ^/(.*)$ https://monsite.fr/$1
    </VirtualHost>

    <VirtualHost *:443>
      ServerName www.monsite.fr
      RedirectMatch ^/(.*)$ https://monsite.fr/$1
    </VirtualHost>

    <VirtualHost *:443>
      ServerName monsite.fr
      SSLEngine On
      SSLCertificateFile    /path_to_cert/server.crt
      SSLCertificateKeyFile /path_to_key/server.key
      DocumentRoot "/opt/monsite.fr/htdocs"
    </VirtualHost>

The first virtual host block will redirect all requests from http://www.monsite.fr to https://monsite.fr. It will also redirect all requests from http://monsite.fr to https://monsite.fr

The second virtual host block will redirect all requests from https://www.monsite.fr to https://monsite.fr.

The third virtual host block will serve the content for https://monsite.fr. Make sure to edit the above mentioned configuration and add the correct path /path_to_cert/server.crt for the SSL certificate and /path_to_key/server.key for the private key.

Upvotes: 1

Related Questions