1

Environment: Ubuntu with Apache.

Trying to setup automatic redirection from http to https.

I have tried:

<VirtualHost *:80> RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} </VirtualHost> <VirtualHost *:443> SSLEngine on SSLCertificateFile <path to your crt file> SSLCertificateKeyFile <path to your private key file> # ... </VirtualHost> 

and

 RewriteEngine on ReWriteCond %{SERVER_PORT} !^443$ RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R,L] 

From mydomain.com --- To ---> (https://) mydomain.com

Any ideas?

2
  • You need to enable .htaccess in /etc/apache/sites-available/mydomain.conf, then create a .htaccess file in root directory (by default /var/www/html) and write the code you have written above. Commented Aug 3, 2019 at 19:14
  • All of the answers given below are blindly following the OP's mistake of trying to use a rewrite to do a redirect. HTTP to HTTPS should be done with a redirect using the "Redirect" directive. No need to load the RewriteEngine with complicated rules, etc. Commented Feb 22, 2023 at 21:23

3 Answers 3

5

Make sure you can access your website both through HTTP and HTTPS. Also make sure mod_rewrite is enabled, then you can add these lines to your .htaccess file.

RewriteEngine On RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] 
Sign up to request clarification or add additional context in comments.

Comments

1

I use this code

<VirtualHost *:80> ServerName foo.com ServerAlias www.foo.com <IfModule mod_rewrite.c> RewriteEngine on RewriteRule ^ - [E=protossl] RewriteCond %{HTTPS} on RewriteRule ^ - [E=protossl:s] RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </IfModule> </VirtualHost> 

Comments

0

First create a virtual host based on this tutorial:
Apache Web server - Setting Up Virtual Hosts

Secondly you can create a Let's encrypt cert and if you use certbot it will automatically configures your Apache and do the redirection:
How To Secure Apache with Let's Encrypt on Ubuntu 18.04

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.