kittygirl
kittygirl

Reputation: 2443

How to switch apache virtualhost from `http` to `https` through apache conf file?

My Apache 2.4 conf file as below:

Listen 80
Listen 443 https

NameVirtualHost *:443
#
<VirtualHost *:443>
ServerAdmin [email protected]
DocumentRoot "/home/websites/example/www"
ServerName example.com
ServerAlias www.example.com

SSLEngine on
SSLCertificateFile "/path/to/www.example.com.cert"
SSLCertificateKeyFile "/path/to/www.example.com.key"
# HSTS (mod_headers is required) (63072000 seconds = 2years)
Header always set Strict-Transport-Security "max-age=63072000;includeSubDomains;"

RewriteEngine On
RewriteCond %{HTTP:Host} ^example.com$
RewriteRule (.*) http://www.example.com$1 [NC,R=301]

RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

</VirtualHost>  

My thought:
As <VirtualHost *:443>, then any setting within <VirtualHost is effective only when apache listen port 443,then RewriteCond %{HTTPS} !=on will never become true,then http:// will not switch to https://.
Then,how to write Apache conf file to make virtualhost *:443 switch http:// to https://?

Upvotes: 0

Views: 48

Answers (1)

symcbean
symcbean

Reputation: 48357

The title of your question is an oxymoron - do you want the same behaviour on port 80 as 443? Do you want to send all your port 80 traffic to port 443? Since a comment in your code mentions HSTS, I will assume the latter.

Declare a default host for port 80, and redirect all the traffic in that virtual host. I would strongly recommend that you use a 302 rather than a 301 redirect, at least until your config is working the way you want.

<VirtualHost *:80>
 ServerAdmin [email protected]
 DocumentRoot "/home/websites/example/EMPTYDIR"
 ServerName example.com

 RewriteEngine On
 RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

</VirtualHost>

(BTW, using your default to handle an explicitly named virtual host is a bit untidy).

Upvotes: 1

Related Questions