Docs / Web Servers / HTTP to HTTPS Redirect with Nginx and Apache

HTTP to HTTPS Redirect with Nginx and Apache

By Admin · Feb 25, 2026 · Updated Apr 24, 2026 · 30 views · 1 min read

Why Redirect?

After installing an SSL certificate, you need to redirect all HTTP traffic to HTTPS. This ensures visitors always use the encrypted connection and helps SEO (Google prefers HTTPS).

Nginx Redirect

# Separate server block for HTTP redirect
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$server_name$request_uri;
}

# HTTPS server block
server {
    listen 443 ssl http2;
    server_name example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    # ... your site configuration
}

Apache Redirect

Using .htaccess:

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

Or in the VirtualHost:

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

WWW to Non-WWW (or vice versa)

# Nginx: www to non-www
server {
    listen 80;
    listen 443 ssl;
    server_name www.example.com;
    return 301 https://example.com$request_uri;
}

Verify Redirect

curl -I http://example.com
# Should show: HTTP/1.1 301 Moved Permanently
# Location: https://example.com/

Was this article helpful?