Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect HTTP to HTTPS on default virtual host without ServerName

On my apache server I'd like to be able to redirect all incoming http requests to the equivalent https request. The catch is that I'd like to be able to do this for my default virtual host without specifying the ServerName and have the redirect work with whatever server name appeared in the request url. I'm hoping for something like this:

NameVirtualHost *:80 <VirtualHost *:80>     RedirectPermanent / https://%{SERVER_NAME}/     ... </VirtualHost> 

Is this possible using Redirect or will I have to resort to Rewrite?

like image 473
highlycaffeinated Avatar asked Jul 23 '12 21:07

highlycaffeinated


People also ask

How do I force Apache to HTTPS?

Redirect HTTP to HTTPS on Apache Virtual Host The second is for the secure port 443. To redirect HTTP to HTTPS for all the pages of your website, first open the appropriate virtual host file. Then modify it by adding the configuration below. Save and close the file, then restart the HTTP sever like this.


2 Answers

Try adding this in your vhost config:

RewriteEngine On RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L] 
like image 167
Jon Lin Avatar answered Oct 11 '22 22:10

Jon Lin


Both works fine. But according to the Apache docs you should avoid using mod_rewrite for simple redirections, and use Redirect instead. So according to them, you should preferably do:

<VirtualHost *:80>     ServerName www.example.com     Redirect / https://www.example.com/ </VirtualHost>  <VirtualHost *:443>     ServerName www.example.com     # ... SSL configuration goes here </VirtualHost> 

The first / after Redirect is the url, the second part is where it should be redirected.

You can also use it to redirect URLs to a subdomain: Redirect /one/ http://one.example.com/

like image 31
orszaczky Avatar answered Oct 11 '22 22:10

orszaczky