How can I automatically redirect HTTP to HTTPS on Apache servers?
Asked Answered
E

13

268

I am trying to set up automatic redirection from HTTP to HTTPS:

From manage.mydomain.com --- To ---> https://manage.mydomain.com

I have tried adding the following to my httpd.conf file, but it didn't work:

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

How can I fix it?

Environment: CentOS with Apache

Errolerroll answered 24/4, 2013 at 19:23 Comment(0)
E
308

I have actually followed this example and it worked for me :)

NameVirtualHost *:80
<VirtualHost *:80>
   ServerName mysite.example.com
   Redirect permanent / https://mysite.example.com/
</VirtualHost>

<VirtualHost _default_:443>
   ServerName mysite.example.com
  DocumentRoot /usr/local/apache2/htdocs
  SSLEngine On
 # etc...
</VirtualHost>

Then do:

/etc/init.d/httpd restart

Errolerroll answered 24/4, 2013 at 20:35 Comment(14)
Note that this is only available if you have access to the VirtualHost file. It is the recommended method.Marjorie
After changing this on httpd.conf, restart apache web server. so that it will reflect and clear your browser cache too.Falconry
This method seems not to work with IE 11. When trying to open domain.com with a redirection to domain.com it is, but a second access to domain.com/folder leads into an error message that IE is not able to open the page. I cannot explain it, but I guess IE caches the redirect and has an issue by resolving the folder through the cache. Firefox works perfectly... I switched to the Rewrite solution by IdemeNaHavaj.Aeschines
I would like to report that this method didn't work for me with Ubuntu 12.4, however the proposed RewriteEngine answer did the trick.Errolerroll
do you have to do a restart? a reload is much less destructive and will bring in the new config file. /etc/init.d/httpd reload || service httpd reloadBookrest
since the purpose was to redirect it to the ssl mode, the line DocumentRoot /usr/local/apache2/htdocs is no longer neededCampy
When redirecting everything you don't even need a DocumentRoot. So you can remove DocumentRoot /usr/local/apache2/htdocs inside <VirtualHost *:80>. You still need DocumentRoot inside <VirtualHost _default_:443> Redirect Request to SSLPelecypod
Notice a great answer (see edit section) is here: serverfault.com/questions/120488/…Sniff
be advised that you will lose all Facebook Likes when doing this -- provided you started collecting your Likes with a http connection! Use JavaScript instead: if (location.protocol !== 'https:') { location.replace('https:${location.href.substring(location.protocol.length)}'); }Refrain
Note that NameVirtualHost seems to be depreciated, This directive currently has no effect.Forthwith
I'm not sure why Redirect permanent is necessary, but on my test machine it only seemed to redirect if permanent was enabled, otherwise it seems like the browser did not redirect.Forthwith
Warning!!! I do not recommend doing it using Apache. You will louse ALL Facebook Likes when doing this (provided you started collecting your Likes with an http connection!Refrain
I think the solution with mod_rewrite is better because it only works for the root of the site.Buie
Yes. The mod_rewrite solution is more flexible, as it can also be applied inside directoryblocks. But the VirtualHost approach is simpler to understand. Recently I started supplementing in PHP as a backup, because my config has broken far too many times due to silly mistakes on my end. The performance you get from doing this on the server level is negligible in most cases anyway. Just to say, one thing does not rule out the other, and your app should not be ignorant as to what protocol was used to perform a request just because you have configured your server correctly.Accuse
W
226
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI}

Apache Redirect HTTP to HTTPS using mod_rewrite

or

Apache: Redirect http to https Apache secure connection – force HTTPS Connections

Womankind answered 24/4, 2013 at 19:27 Comment(12)
This is a better solution than the approved one, because it works even if you are behind an SSL offloader like Pound or BigIP. Those offloader will often pass all the traffic onto the same port,and the approved solution won't work in that specific casePapaya
@spiritoo Not so. The Apache docs specifically say that this is one of those situations where you should not use mod_rewrite and should rather use Redirect: httpd.apache.org/docs/2.4/rewrite/avoid.htmlIver
@LukeMadhanga Apache docrecommands using Redirect for performance. But still, the RewriteEngine solution is better, in the sense of more generic, because it works even in the case I described (offloading). The goal of my comment is to provide every user the key to choose between the two answers. Some people want generic procedures (big corps), others want performance... it's a free choice.Papaya
This is great, however, if you want to make it greater then add this [R=302,L,QSA] so any parameters are also passed to the secure page. It should look like: %{REQUEST_URI} [R=302,L,QSA]Lannie
I used these lines and when try to load page, response is "Failed to load resource: net::ERR_CONNECTION_REFUSED". What am i doing wrong?Objectify
@SvetoslavMarinov This comment implies, "that [QSA] is automatically added when [R] is used in this context and no ? is present in the rewritten URL so it's superfluous here".Crookes
@Objectify - have you forgotten dash after [] section? I had infinite redirect there.Baffle
The problem with just using redirect is that if you put in the URL of any page in your website as HTTP, it will not redirect to HTTPS. Only the home/default/root/index page will. And, no, that's not good enough.Encircle
Warning!!! I do not recommend doing it using Apache. You will louse ALL Facebook Likes when doing this (provided you started collecting your Likes with an http connection!Refrain
Attention: I recommend using SERVER_NAME instead of HTTP_HOST in case you have more than one virtual host! Otherwise you rewrite with the IP and loose the query hostname. Spent a couple of hours trying to figure out why apache was calling the wrong host...Bradfordbradlee
In coverting http to https, you would use Rewrite if you don't care if the client to server connection is secure. In other words, you are using an unsecure connection to make a connection to some other service that only supports a secure connection. Generally, that's not what you want to do, and that's why you see the recommendation for using Redirect. You use Redirect when you want the client to sever connection to be secure. In most situations, that's probably what you want to do.Faitour
The space in ^ https... is required for some reason. I was editing my config and some rules did not have a space, but http -> https did; I seriously thought this was a mistake. When I removed it, I discovered later it was not working. This syntax strike me as inconsistent or odd at best. However, the web app should check if the server support HTTPS; it should probably be possible to configure the app to automatically redirect regardless of server config. Relying on server config can be risky as: 1. Things can change doing updates. 2. The syntax is strange to many devs.Accuse
H
144

I searched for apache redirect http to https and landed here. This is what I did on Ubuntu:

1) Enable modules

sudo a2enmod rewrite
sudo a2enmod ssl

2) Edit your site configuration

Edit file

/etc/apache2/sites-available/000-default.conf

The content should be:

<VirtualHost *:80>
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</VirtualHost>

<VirtualHost *:443>
    SSLEngine on
    SSLCertificateFile    <path to your certificate file>
    SSLCertificateKeyFile   <path to your private key file>

    # Rest of your site configuration
    # ...
</VirtualHost>

Note that the SSL module requires a certificate. You will need to specify an existing one (if you bought one) or to generate a self-signed certificate by yourself.

3) Restart Apache

sudo service apache2 restart
Howling answered 3/11, 2014 at 15:49 Comment(5)
Work with Ubuntu 16.04 & Apache2. Thanks!Quisling
For ip address redirect myipaddress to myipaddress worked. Thanks.Largehearted
This solution is much more robust when you have some nonstandard config. Thanks!Bandler
This solution works for me (Apache/2.4.41 + Ubuntu 20.04.3) but I get HTTP status code 302. How to get status code 301?Scent
Works fine on Debian 11, thanks.Hillier
R
18

Using mod_rewrite is not the recommended way. Instead, use a virtual host and redirect.

In case if you are inclined to do using mod_rewrite:

RewriteEngine On
# This will enable the Rewrite capabilities

RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS

RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
# This rule will redirect users from their original location, to the same 
location but using HTTPS.
# I.e., http://www.example.com/foo/ to https://www.example.com/foo/
# The leading slash is made optional so that this will work either in
# httpd.conf or .htaccess context

Reference: Httpd Wiki - RewriteHTTPToHTTPS

If you are looking for a 301 Permanent Redirect, then the redirect flag should be as,

 R=301

so the RewriteRule will be like,

RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=301,L]
Raimondo answered 15/11, 2017 at 7:59 Comment(0)
C
14

I needed this for something as simple as redirecting all HTTP traffic from the default Apache home page on my server to one served over HTTPS.

Since I'm still quite green when it comes to configuring Apache, I prefer to avoid using mod_rewrite directly and instead went for something simpler like this:

<VirtualHost *:80>
  <Location "/">
     Redirect permanent "https://%{HTTP_HOST}%{REQUEST_URI}"
  </Location>
</VirtualHost>

<VirtualHost *:443>
  DocumentRoot "/var/www/html"
  SSLEngine on
  ...
</VirtualHost>

I like this because it allowed me to use Apache variables. That way, I didn't have to specify the actual host name since it's just an IP address without an associated domain name.

References: Using RedirectMatch with HTTP_HOST in the destination

Crocked answered 28/3, 2020 at 18:44 Comment(6)
I got this: ERR_INVALID_REDIRECT. seems that parameters are not defined here.Carrol
Worked for me and was exactly what I was looking for as I did not want to use ModRewrite with Apache 2.4.38. The only difference is, that I used <Location /> as the quotes are not needed there. (Not tested with the quotes.)Vein
I got ERR_INVALID_REDIRECT as well because it redirects to the litteral string https://%{HTTP_HOST}%{REQUEST_URI}.Silk
@Silk are you running your apache server behind a proxy? If HTTP_HOST is not being expanded, then it's likely due to the server not seeing the Host: header in the requestCrocked
Attention: I recommend using SERVER_NAME instead of HTTP_HOST in case you have more than one virtual host! Otherwise you rewrite with the IP and loose the query hostname. Spent a couple of hours trying to figure out why apache was calling the wrong host...Bradfordbradlee
@Bradfordbradlee good tip. SERVER_NAME has to be manually configured on the server, but otherwise that seems to be a solid alternative when dealing with multiple virtual hostsCrocked
B
13

Actually, your topic is belongs on Server Fault, but you can still try to check these .htaccess directives:

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*) https://%{HTTP_HOST}/$1
Boutte answered 24/4, 2013 at 19:34 Comment(0)
O
11

If you have Apache 2.4, check file 000-default.conf. Remove DocumentRoot and add:

Redirect permanent / https://[your-domain]/
Ossification answered 27/1, 2018 at 22:54 Comment(0)
A
7

Server version: Apache 2.4.29 (Ubuntu)

After a long search on the web and in the official documentation of Apache HTTP Server, the only solution that worked for me came from /usr/share/doc/apache2/README.Debian.gz

To enable SSL, type (as user root):

    a2ensite default-ssl
    a2enmod ssl

In the file /etc/apache2/sites-available/000-default.conf, add the

Redirect "/" "https://sub.domain.com/"

<VirtualHost *:80>

    #ServerName www.example.com
    DocumentRoot /var/www/owncloud
    Redirect "/" "https://sub.domain.com/"

That's it.


P.S: If you want to read the manual without extracting:

gunzip -cd /usr/share/doc/apache2/README.Debian.gz
Algerian answered 1/11, 2018 at 15:14 Comment(2)
Or marginally less typing and easier to rememeber; read the readme without extracting: zcat /usr/share/doc/apache2/README.Debian.gzJewfish
@JeremyDavis Yeah, or maybe even use zless /usr/share/doc/apache2/README.Debian.gz (instead of zcat) so you can scroll through it without printing it all into the terminal session.Kaitlinkaitlyn
D
6

This code work for me.

# ----------port 80----------
RewriteEngine on
# redirect http non-www to https www
RewriteCond %{HTTPS} off
RewriteCond %{SERVER_NAME} =example.com
RewriteRule ^ https://www.%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]

# redirect http www to https www
RewriteCond %{HTTPS} off
RewriteCond %{SERVER_NAME} =www.example.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]

# ----------port 443----------
RewriteEngine on
# redirect https non-www to https www
RewriteCond %{SERVER_NAME} !^www\.(.*)$ [NC]
RewriteRule ^ https://www.%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]

Dreddy answered 5/4, 2017 at 1:53 Comment(0)
S
5

For me, this worked:

RewriteEngine on
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
Staats answered 5/11, 2020 at 20:52 Comment(0)
Z
4

Please try this one in Apache's Virtualhosting configuration and then reload the Apache service:

RewriteEngine On

RewriteCond %{HTTPS} off

RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI}
Zoogeography answered 3/1, 2019 at 7:39 Comment(0)
W
2

This worked for me:

RewriteCond %{HTTPS} =off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [QSA,L,R=301]
Wherein answered 5/4, 2016 at 7:41 Comment(0)
O
1

This specific issue is covered in the Apache docs here. Use an Apache configuration modeled on the one in the excerpt below (typically you'll want to name the file something like com.example.www.conf).

To redirect http URLs to https, do the following:

<VirtualHost *:80>
    ServerName www.example.com
    Redirect "/" "https://www.example.com/"
</VirtualHost>

<VirtualHost *:443>
    ServerName www.example.com
    # ... SSL configuration goes here
</VirtualHost>
Orpine answered 11/6, 2023 at 16:45 Comment(6)
I don't understand why this answer was downvoted. I'm interested to know why, I'm willing to delete the answer if it can be explained why I shouldn't have posted it.Orpine
The answer is throwing a reference, copying some documentation, and is *** *** unspecific *** **** (for instance, what is the issue?), without explaining the gist of it. It is somewhat equivalent to a code dump. If the link breaks, it is essentially a "try this" answer. From the Help Center: "...always explain why the solution you're presenting is appropriate and how it works".Johannajohannah
Somewhat related: What do we do with answers that are entirely copied and improperly attributed (only a "reference" link or similar is included)?Johannajohannah
@PeterMortensen The issue is "How can I automatically redirect HTTP to HTTPS on Apache servers?", and the quoted config setting is specifically addressing that: "To redirect http URLs to https...". If the link breaks, someone can switch it to an archive.org version of the link (something I frequently do for old answers where the link has broken). I don't see how the second link you added is at all related, as I'm not passing off someone else's written-up blog-post-style explanation as my own. The format of my answer is basically the same of that of the top-voted answer.Orpine
@PeterMortensen I've added a sentence explaining where the excerpt should be placed, in case that's not clear.Orpine
Regarding "...always explain why the solution you're presenting is appropriate and how it works": how much previous knowledge should we be expecting from the person asking the question? My original answer was assuming they were already familiar with Apache config files.Orpine

© 2022 - 2024 — McMap. All rights reserved.