Search code examples
debianapache2http-redirectapache-config

APache2 http -> https forwarding


I am stuck with forwarding http to https requests in Apache2:

    <VirtualHost *:80>
       ServerName example.com
       DocumentRoot /var/www
       Redirect permanent / https://example.com/
    </VirtualHost>
    
    <VirtualHost _default_:443>
      ServerName example.com
      DocumentRoot /var/www
      SSLEngine On
     # etc...
    </VirtualHost>

The site is available at https://example.com/mysite but if I enter http://example.com/mysite, I get forwarded to https://example.com/mysitemysite (note the mysitemysite instead of mysite in the end).

What do I need to change in the config file to prevent that issue?

Thanks for any help!


Solution

  • Instead of using Redirect permanent to achieve https, you should use a Rewrite rule. Replace your code with the following:

    <VirtualHost *:80>
       ServerName example.com
       DocumentRoot /var/www
       RewriteEngine On
       RewriteCond %{HTTPS} off
       RewriteRule (.*) https://%{SERVER_NAME}/ [R,L]
    </VirtualHost>
    
    <VirtualHost _default_:443>
      ServerName example.com
      DocumentRoot /var/www
      SSLEngine On
     # etc...
    </VirtualHost>
    
    

    Here we're using a Rewrite rule to activate your website SSL.

       RewriteEngine On
       RewriteCond %{HTTPS} off
       RewriteRule (.*) https://%{SERVER_NAME}/ [R,L]
    

    And make sure that you have Rewrite module enabled in your apache. To enable the modrewrite, access the apache2 module directory cd /etc/apache2/mods-available run the following command a2enmod rewrite.load and restart your apache2 service apache2 restart