Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting HTTP to HTTPS with Apache

I have an issue using mod_rewrite to force redirection of HTTP requests to HTTPS using Apache 2.2.22 on Ubuntu Server 12.04.

My /etc/apache2/sites-available/default file is as follows:

    <VirtualHost *:80>
        RewriteEngine On
        RewriteCond %{SERVER_PORT} !^443$
        RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R,L]
    </VirtualHost>

The HTTPS host is defined in default-ssl in the same directory.

Visiting the server's local IP address, the redirect appears to work fine. However, accessing it via the FQDN, it doesn't. Using the FQDN, the site is available at port 5443, which is mapped in the firewall to 443 on the server, so perhaps that has something to do with the problem. I cannot just use port 443 directly, as it is in use on this IP address by another server.

To further clarify, the following are valid links:

    https://website:5443
    https://192.168.200.80:443

The redirect works here:

    http://192.168.200.80

But the following gives a 400 Bad Request, and this is where the redirect is needed:

    http://website:5443/

"Your browser sent a request that this server could not understand. Reason: You're speaking plain HTTP to an SSL-enabled server port. Instead use the HTTPS scheme to access this URL, please."

like image 528
dutchgold92 Avatar asked Jul 25 '13 09:07

dutchgold92


People also ask

How do I automatically redirect HTTP to HTTPS on Apache server?

In Apache, the preferred way to redirect HTTP to HTTPS is to configure the 301 redirect in the domain's virtual host.

Can you forward HTTP to HTTPS?

If you are using the popular Apache Web server, you can easily redirect all traffic from unsecured HTTP to HTTPS. When a visitor goes to your site will be redirected to the secure HTTPS protocol. The server must allow you to use module mod_rewrite, but it's not a problem for most webhosting providers.


1 Answers

This is totally possible. The following redirects all http to the https url.

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

make sure you load the rewrite module mod_rewrite and enable it.

like image 138
Steven Soroka Avatar answered Oct 25 '22 07:10

Steven Soroka