258

Environment Centos with apache

Trying to setup 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 but it didn't work

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

Any ideas?

Jesse Nickles
  • 1,435
  • 1
  • 17
  • 25
Deano
  • 11,582
  • 18
  • 69
  • 119

13 Answers13

298

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

Ming
  • 4,110
  • 1
  • 29
  • 33
Deano
  • 11,582
  • 18
  • 69
  • 119
  • 7
    Note that this is only available if you have access to the VirtualHost file. It is the recommended method. – The Thirsty Ape Sep 25 '13 at 23:54
  • 4
    After changing this on httpd.conf, restart apache web server. so that it will reflect and clear your browser cache too. – Suriyan Suresh Oct 16 '13 at 05:38
  • 1
    This method seems not to work with IE 11. When trying to open http://domain.com with a redirection to https://domain.com it is, but a second access to http://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. – Rick-Rainer Ludwig Feb 27 '14 at 20:14
  • 2
    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. – Deano Jul 25 '14 at 14:37
  • 5
    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 reload` – Rebecca Dessonville Jan 06 '16 at 15:42
  • 4
    since the purpose was to redirect it to the ssl mode, the line `DocumentRoot /usr/local/apache2/htdocs` is no longer needed – Abel Callejo Aug 04 '16 at 08:59
  • 2
    When redirecting everything you don't even need a DocumentRoot. So you can remove `DocumentRoot /usr/local/apache2/htdocs` inside ``. You still need `DocumentRoot` inside `` [Redirect Request to SSL](https://wiki.apache.org/httpd/RedirectSSL) – kimbaudi Dec 16 '16 at 00:18
  • Notice a great answer (see edit section) is here: https://serverfault.com/questions/120488/redirect-url-within-apache-virtualhost – Rayee Roded Sep 01 '17 at 19:49
  • 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)}'); }` – MeSo2 Oct 18 '20 at 16:02
  • Note that `NameVirtualHost` seems to be depreciated, [This directive currently has no effect.](http://httpd.apache.org/docs/2.4/mod/core.html#namevirtualhost) – jrh Apr 25 '21 at 15:31
  • 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. – jrh Apr 25 '21 at 15:36
  • **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! – MeSo2 May 11 '21 at 02:47
  • I think the solution with mod_rewrite is better because it only works for the root of the site. – Luis Vazquez Jun 29 '23 at 00:09
  • Yes. The `mod_rewrite` solution is more flexible, as it can also be applied inside `directory`blocks. 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. – Jacob Aug 04 '23 at 08:20
211
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI}

http://www.sslshopper.com/apache-redirect-http-to-https.html

or

http://www.cyberciti.biz/tips/howto-apache-force-https-secure-connections.html

AD7six
  • 63,116
  • 12
  • 91
  • 123
IdemeNaHavaj
  • 2,297
  • 1
  • 12
  • 10
  • 3
    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 case – spiritoo Jul 31 '15 at 19:34
  • 4
    @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: https://httpd.apache.org/docs/2.4/rewrite/avoid.html – Luke Madhanga Nov 23 '15 at 15:07
  • 5
    @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. – spiritoo Dec 11 '15 at 09:16
  • 25
    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] – Svetoslav Marinov Jun 11 '16 at 15:19
  • 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? – Serkan Jun 09 '17 at 09:12
  • 2
    @SvetoslavMarinov This [comment](https://stackoverflow.com/questions/13977851/htaccess-redirect-to-https-www?noredirect=1&lq=1#comment73677715_13997498) 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". – Volker E. Jan 15 '18 at 16:23
  • @Serkan - have you forgotten dash after [] section? I had infinite redirect there. – Leos Literak Jul 16 '18 at 17:33
  • 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. – Bobort Feb 13 '19 at 22:02
  • **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! – MeSo2 May 11 '21 at 02:45
  • 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... – stackoverflowed Dec 15 '22 at 14:07
  • 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. – Tom Rutchik Jan 03 '23 at 21:45
  • 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. – Jacob Aug 04 '23 at 08:04
137

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 config

Edit file

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

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 crt file>
    SSLCertificateKeyFile   <path to your private key file>

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

3) Restart apache2

sudo service apache2 restart
Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129
16

Using mod_rewrite is not the recommended way instead use 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 redirect flag should be as,

 R=301

so the RewriteRule will be like,

RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=301,L]
Vincy
  • 189
  • 2
  • 5
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: https://stackoverflow.com/a/40291044/2089675

smac89
  • 39,374
  • 15
  • 132
  • 179
  • 1
    I got this: ERR_INVALID_REDIRECT. seems that parameters are not defined here. – mahyard Feb 18 '21 at 15:23
  • 2
    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 `` as the quotes are not needed there. (Not tested with the quotes.) – Tino Jul 14 '21 at 20:59
  • I got ERR_INVALID_REDIRECT as well because it redirects to the litteral string `https://%{HTTP_HOST}%{REQUEST_URI}`. – bfontaine Jun 08 '22 at 09:33
  • @bfontaine 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 request – smac89 Jun 08 '22 at 09:58
  • 1
    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... – stackoverflowed Dec 15 '22 at 14:07
  • @stackoverflowed 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 hosts – smac89 Dec 16 '22 at 02:31
13

Actually, your topic is belongs on https://serverfault.com/ but you can still try to check these .htaccess directives:

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*) https://%{HTTP_HOST}/$1
Community
  • 1
  • 1
11

If you have Apache2.4 check 000-default.conf - remove DocumentRoot and add

Redirect permanent / https://[your-domain]/
thor
  • 21,418
  • 31
  • 87
  • 173
indifference
  • 111
  • 2
  • 4
7

Server version: Apache/2.4.29 (Ubuntu)

After long search on the web and in the official documentation of apache, 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
DimiDak
  • 4,820
  • 2
  • 26
  • 32
  • Or marginally less typing and easier to rememeber; read the readme without extracting: zcat /usr/share/doc/apache2/README.Debian.gz – Jeremy Davis Dec 09 '21 at 07:05
  • 1
    @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. – mwfearnley Jun 16 '23 at 11:21
  • 1
    @mwfearnley - Good call! :) – Jeremy Davis Jun 19 '23 at 01:13
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]

user7817632
  • 69
  • 1
  • 1
5

for me this worked

RewriteEngine on
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
dasl
  • 426
  • 7
  • 6
4

Please try this one in apache Virtualhosting configuration and then reload apache service

RewriteEngine On

RewriteCond %{HTTPS} off


RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI}
MD IRFAN
  • 81
  • 2
2

This worked for me:

RewriteCond %{HTTPS} =off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [QSA,L,R=301]
Fint
  • 595
  • 5
  • 5
-1

This specific issue is covered in the Apache docs here:

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>
Nathan Wailes
  • 9,872
  • 7
  • 57
  • 95
  • 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. – Nathan Wailes Jun 12 '23 at 18:12