How to Redirect HTTP to HTTPS on a Linux Web Server

Switching your website to HTTPS is crucial for securing user data and boosting trust, while also improving SEO and meeting modern web standards. This guide simplifies the process of redirecting all HTTP traffic to HTTPS on Linux servers using Apache or Nginx. With practical examples and tips, you’ll ensure a seamless, secure experience for your visitors.

Why redirect to HTTPS?

Switching to HTTPS (SSL/TLS) ensures:

  • Encrypted communication between users and your server
  • Improved SEO ranking (Google prefers HTTPS)
  • Trust indicators such as the padlock symbol in the browser
  • Compliance with modern web standards

Once you have installed an SSL certificate, the next step is to route all traffic via the secure HTTPS protocol.

Apache: Redirect HTTP to HTTPS

If your server uses Apache, you can configure the redirection as follows.

Step 1: Activate the rewrite module

Make sure that mod_rewrite is activated:

sudo a2enmod rewrite
sudo systemctl neustart apache2

Step 2: Update the configuration of your virtual host

Open your HTTP(port 80) Configuration file for the virtual host:

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

Then insert this within the block:

RewriteEngine Ein
RewriteCond %{HTTPS} aus
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Save and exit the file and then restart Apache:

sudo systemctl restart apache2

Nginx: Redirect HTTP to HTTPS

If your server uses Nginx, the redirection is performed in the server block of the website.

Step 1: Edit the Nginx configuration file

sudo nano /etc/nginx/sites-available/default

Step 2: Add a redirect block

Add this block above your existing server block for HTTPS:

server {
    listen 80;
    server_name ihredomain.de www.yourdomain.com;

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

Replace yourdomain.com with your actual domain name. Then test and reload:

sudo nginx -t
sudo systemctl reload nginx

Optional: Redirect from www to non-www (or vice versa)

You can also combine HTTPS enforcement with the canonicalization of domains.

Example: Redirection from www to non-www (with HTTPS) in Nginx:

server {
    listen 80;
    server_name www.yourdomain.com;

    return 301 https://yourdomain.com$request_uri;
}

Testing the redirection

Once you have made the changes, test them:

Conclusion

Redirecting HTTP to HTTPS on your Linux server is a straightforward way to enhance security and user trust. By configuring Apache or Nginx as outlined, testing with practical examples, and following best practices, you ensure a smooth transition to a secure website. Keep your SSL certificate valid and monitor redirects to maintain a professional, SEO-friendly online presence.