Website Vidya
UncategorizedStep-by-Step Guide

How to Redirect HTTP to HTTPS in Nginx

If you’re running a website today and it’s still accessible over plain HTTP, you’re already behind. Modern browsers flag non-HTTPS sites as “Not Secure,” search engines favor encrypted websites, and users are far more cautious about where t...

RR
Rajesh RayLead Systems Educator
Published:
6 min read
PDF Cheat Sheet
How to Redirect HTTP to HTTPS in Nginx
AI Executive SummaryCORE CIS AI

6 min read

If you’re running a website today and it’s still accessible over plain HTTP, you’re already behind. Modern browsers flag non-HTTPS sites as “Not Secure,” search engines favor encrypted websites, and users are far more cautious about where t...

Key Highlights
  • Why Redirecting HTTP to HTTPS Is Non-Negotiable
  • Prerequisites Before You Redirect
  • Understanding How Nginx Handles HTTP and HTTPS
Grounded in full engineering runbookCORE CIS Ai Engine

Interactive Builder for this Guide

Build your custom nginx syntax (How to Redirect HTTP to HTTPS in Nginx)

Generated Config Output
server {
    listen 80;
    listen [::]:80;
    server_name app.example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name app.example.com;

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

    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    gzip on;
    gzip_types text/plain text/css application/json application/javascript application/xml;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}
Production Nginx reverse proxy -> 127.0.0.1:3000 for app.example.com.
Flag-by-Flag Breakdown
server_nameBinds this virtual host to app.example.com
return 301 https://...Redirects all plain HTTP requests permanently to TLS/HTTPS
proxy_pass http://127.0.0.1:3000Forwards HTTP + WebSocket requests to local application server
X-Content-Type-Options / X-Frame-OptionsProtects users against MIME sniffing and clickjacking

If you’re running a website today and it’s still accessible over plain HTTP, you’re already behind. Modern browsers flag non-HTTPS sites as “Not Secure,” search engines favor encrypted websites, and users are far more cautious about where they enter their data.

That’s why learning how to redirect HTTP to HTTPS in Nginx isn’t just a technical improvement—it’s a trust upgrade.

In this guide, I’ll walk you through simple, production-ready ways to redirect HTTP to HTTPS in Nginx, explain why certain methods are better than others, and share SSL best practices that most tutorials completely skip. This isn’t copied config fluff. It’s based on how Nginx actually behaves in real-world server environments.

Whether you’re running a blog, SaaS product, eCommerce store, or company website, this article will help you do HTTPS the right way.

Advertisement

Why Redirecting HTTP to HTTPS Is Non-Negotiable

Before touching configuration files, let’s clarify why this matters.

1. Security Comes First

HTTP traffic is sent in plain text. Anyone on the same network can intercept usernames, passwords, cookies, or form data. HTTPS encrypts everything using SSL/TLS.

2. Google Uses HTTPS as a Ranking Signal

Google confirmed HTTPS as a ranking factor years ago. While it’s not the biggest signal, insecure sites are at a disadvantage—especially for competitive keywords.

3. Browsers Actively Warn Users

Chrome, Firefox, and Safari now show warnings for non-HTTPS pages. That alone can destroy user trust and increase bounce rates.

4. Modern Web Features Require HTTPS

HTTP/2, HTTP/3, service workers, and many APIs simply won’t work properly without HTTPS.

Advertisement

So yes—redirecting HTTP to HTTPS in Nginx is mandatory, not optional.


Prerequisites Before You Redirect

Before implementing any redirect, make sure these basics are in place.

1. A Valid SSL Certificate

Your domain must already have an SSL certificate installed. This can be:

  • Let’s Encrypt (free and widely trusted)
  • Cloudflare Origin Certificate
  • Paid certificates (DigiCert, Sectigo, etc.)

If HTTPS doesn’t load at all, don’t set redirects yet. You’ll lock users out.

2. Access to Nginx Configuration

You should have SSH access or permission to edit Nginx config files, usually located at:

Advertisement
/etc/nginx/nginx.conf
/etc/nginx/sites-available/

3. Confirm HTTPS Works First

Open your site directly:

https://yourdomain.com

No warnings. No errors. Only then proceed.


Understanding How Nginx Handles HTTP and HTTPS

Nginx treats HTTP and HTTPS as separate server blocks:

  • Port 80 → HTTP
  • Port 443 → HTTPS

Your redirect logic should always live in the port 80 server block.

This separation is what makes Nginx fast—and also what confuses beginners.


This is the best-practice method, used in production environments.

Basic HTTP to HTTPS Redirect

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

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

Why This Method Is Best

  • Uses a 301 permanent redirect (SEO friendly)
  • Preserves full URL path and query strings
  • Minimal logic = fewer bugs
  • Fast and efficient (no rewrite overhead)

This single line does most of the heavy lifting:

return 301 https://$host$request_uri;

It tells Nginx:

“Whatever came in on HTTP, permanently send it to the same URL over HTTPS.”

That’s exactly what you want.


Redirecting HTTP to HTTPS for a Single Domain

If your server hosts multiple sites, you may want to redirect only one domain.

server {
    listen 80;
    server_name example.com;

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

This avoids accidentally redirecting other virtual hosts on the same server.


Redirecting Both www and Non-www Correctly

One common mistake is redirecting HTTP to HTTPS but forgetting canonical domain consistency.

Here’s a clean setup:

Force HTTPS + Non-www

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

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

Force HTTPS + www

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

    return 301 https://www.example.com$request_uri;
}

Pick one canonical version and stick to it.


Avoid This Common Nginx Redirect Mistake

Many guides still recommend rewrite rules like this:

rewrite ^ https://$host$request_uri? permanent;

While this works, it’s not ideal.

Why return Is Better Than rewrite

  • return stops processing immediately
  • rewrite continues parsing rules
  • return is faster and cleaner
  • Easier to read and debug

In modern Nginx setups, use return, not rewrite.


Testing Your Redirect Before Going Live

Never reload Nginx blindly.

Step 1: Test Configuration

nginx -t

You should see:

syntax is ok
test is successful

Step 2: Reload Nginx

sudo systemctl reload nginx

Reload is safer than restart—no dropped connections.


Verifying the Redirect Properly

curl -I http://yourdomain.com

Expected output:

HTTP/1.1 301 Moved Permanently
Location: https://yourdomain.com/

Browser Test

  • Open http://yourdomain.com
  • It should immediately switch to https://

No delay. No redirect chains.


SSL Best Practices Most People Ignore

Redirecting traffic is only half the job. Let’s talk about doing HTTPS correctly.


1. Use Strong TLS Versions Only

Inside your HTTPS server block:

ssl_protocols TLSv1.2 TLSv1.3;

Disable older versions like TLS 1.0 and 1.1—they’re insecure.


2. Enable HTTP Strict Transport Security (HSTS)

HSTS tells browsers:

“Never load this site over HTTP again.”

add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

⚠️ Enable this only after HTTPS works perfectly.


3. Use Secure SSL Ciphers

ssl_prefer_server_ciphers on;
ssl_ciphers HIGH:!aNULL:!MD5;

This reduces exposure to weak encryption attacks.


4. Enable OCSP Stapling

ssl_stapling on;
ssl_stapling_verify on;

This improves SSL handshake speed and trust validation.


5. Use HTTP/2 for Performance

listen 443 ssl http2;

HTTP/2 works only over HTTPS and improves page load times.


Handling Redirect Loops (A Real-World Issue)

If your site gets stuck in a redirect loop, it’s usually due to:

  • Redirect rules inside the HTTPS block
  • Reverse proxy or CDN misconfiguration
  • Application-level redirects (WordPress, Laravel, etc.)

Rule of Thumb

  • Redirect only in port 80
  • Never redirect HTTPS to HTTPS

If you’re behind Cloudflare or a load balancer, make sure Nginx knows the original protocol.


HTTP to HTTPS Redirect Behind a Reverse Proxy

If Nginx sits behind a proxy:

if ($http_x_forwarded_proto = 'http') {
    return 301 https://$host$request_uri;
}

This prevents false redirects when SSL is terminated upstream.


SEO Considerations When Redirecting HTTP to HTTPS

A proper HTTPS migration should:

  • Use 301 redirects, not 302
  • Avoid redirect chains
  • Update canonical tags
  • Update sitemap URLs
  • Update Google Search Console property

Done correctly, rankings remain stable—or improve.


Final Thoughts: Do HTTPS Once, Do It Right

Learning how to redirect HTTP to HTTPS in Nginx is one of those skills that pays off immediately. It improves security, boosts trust, helps SEO, and future-proofs your website.

The key takeaway is simple:

  • Redirect only from port 80
  • Use return 301
  • Verify SSL before forcing redirects
  • Follow modern SSL best practices

If you implement HTTPS cleanly today, you won’t have to fix broken redirects, SEO drops, or security warnings tomorrow.

And in server administration, that’s a win worth taking.


If you’d like, I can also help you:

  • Optimize SSL configs for Let’s Encrypt
  • Fix redirect loops
  • Create a complete production-grade Nginx SSL config
  • Write FAQs or schema-ready snippets for this article

Just tell me 👍

RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout