Redirect HTTP to HTTPS in Nginx

All login credentials transferred over plain HTTP can easily be sniffed by a MITM attacker, but it is not enough to encrypt the login forms. If you are visiting plain HTTP pages while logged in, your session can be hijacked, and not even two-factor authentication will protect you. To protect all info sent between your visitors – which includes you – and your web server, we will redirect all requests that are coming over plain HTTP to the HTTPS equivalent.

Redirect All Sites

server {
    listen 80 default_server;

    server_name _;

    return 301 https://$host$request_uri;
}

Redirect Specific Sites

server {
    listen 80;

    server_name foo.com;
    return 301 https://foo.com$request_uri;
}

Optional: App Configuration

server {
    listen 443 ssl default_server;
    server_name foo.com;
}

server {
    listen 443 ssl;
    server_name bar.com;
}

# and so on...

How to Redirect HTTP to HTTPS in apache

Install modules

yum install -y mod_ssl  mod_rewrite

Enable modules

a2enmod rewrite
a2enmod ssl

Method 1

using rewrite module

<VirtualHost *:80>
ServerName www.yourdomain.com
  
RewriteEngine On 
RewriteCond %{HTTPS} !=on 
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
</VirtualHost>

Method 2

using redirect method

<VirtualHost *:80>
ServerName www.yourdomain.com 
  
Redirect permanent / https://www.yourdomain.com/
</VirtualHost>