How to Force HTTPS Safely: Redirect Rules for Nginx, Apache, and Cloud Platforms
https-redirectnginxapachecdnbest-practices

How to Force HTTPS Safely: Redirect Rules for Nginx, Apache, and Cloud Platforms

AAlex Rowan
2026-06-13
10 min read

Learn how to force HTTPS safely with practical redirect patterns for Nginx, Apache, CDNs, and proxied cloud setups.

Forcing HTTPS sounds simple, but safe redirecting depends on where TLS terminates, how your proxy headers are set, and whether your application already tries to enforce secure URLs. This guide shows how to implement a clean HTTP-to-HTTPS redirect on Nginx, Apache, and common cloud or CDN layers without creating redirect loops, breaking health checks, or leaving mixed-content issues behind. It is also designed as a checklist you can revisit monthly or quarterly, because redirect behavior often changes after certificate renewals, CDN updates, load balancer changes, migrations, and app deployments.

Overview

The goal of a force HTTPS redirect is straightforward: any request that arrives over plain HTTP should be sent to the equivalent HTTPS URL with a permanent redirect, usually a 301 redirect HTTP to HTTPS. In practice, the correct place to do that depends on your stack.

If your server handles TLS directly, the redirect can live in Nginx or Apache. If a CDN, reverse proxy, or cloud load balancer terminates TLS first, redirect logic may need to happen at the edge instead of on the origin. If both layers enforce HTTPS without understanding the original request scheme, you can get a loop that bounces a user between HTTP and HTTPS or between proxy and origin.

A safe setup usually follows a simple order:

  1. Make sure a valid certificate is already installed and serving correctly on HTTPS.
  2. Confirm the site works over HTTPS before you redirect all traffic.
  3. Add one redirect rule in the correct layer first, not in every layer at once.
  4. Test for loops, broken assets, login issues, callback URLs, and health checks.
  5. Only after redirects are stable, consider adding HSTS.

That order matters. Redirecting before HTTPS works turns a partial issue into a full outage. Adding duplicate rules across app, web server, and CDN makes troubleshooting harder. Enabling HSTS too early can lock browsers into HTTPS while your deployment is still inconsistent.

If you still need certificate setup help, see Let's Encrypt on Ubuntu: Step-by-Step Setup for Current LTS Releases, Let's Encrypt for Nginx: Complete Setup, Redirects, and Renewal Checklist, and Let's Encrypt for Apache: Complete Setup, VirtualHosts, and Renewal Checklist.

Nginx: minimal and safe redirect

On Nginx, the cleanest pattern is usually a dedicated server block listening on port 80 that only performs the redirect.

server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;

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

This is the most common nginx HTTPS redirect pattern because it is easy to audit and avoids mixing redirect logic into the TLS-enabled block. Your HTTPS server block should then serve the actual site on port 443.

If Nginx sits behind a proxy or load balancer, do not assume $scheme reflects the browser-facing protocol unless you have correctly configured trusted proxy headers. In proxied setups, redirect decisions often belong at the edge.

Apache: canonical redirect patterns

On Apache, you can enforce HTTPS inside the port 80 VirtualHost or with mod_rewrite. A simple VirtualHost redirect is often easier to maintain.

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

If you need to preserve hostnames dynamically, mod_rewrite is common:

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com

    RewriteEngine On
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</VirtualHost>

This is a standard apache HTTPS redirect approach, but it should be used carefully in shared configurations where inherited rewrite rules may already exist.

Cloud and CDN platforms

If you use Cloudflare, a managed load balancer, or a cloud application gateway, edge redirects are often the cleanest option. They reduce unnecessary requests to the origin and avoid confusion about the original request scheme. The main caution is consistency: if the edge forces HTTPS, your origin should not also guess at client protocol incorrectly.

With CDNs and reverse proxies, pay close attention to forwarded headers such as X-Forwarded-Proto or equivalent platform variables. Application frameworks and origin servers need these headers to understand whether the original browser request was secure. If they do not trust or parse them correctly, they may try to force HTTPS again and trigger a loop.

What to track

A redirect rule is not something you configure once and forget. The most stable teams track a small set of variables whenever certificates renew, DNS changes, infrastructure moves, or application settings change. If you want a reliable force HTTPS redirect setup, these are the things worth monitoring.

1. Redirect location

Document where HTTPS enforcement lives today:

  • CDN or edge platform
  • Cloud load balancer or ingress controller
  • Nginx or Apache on the origin server
  • Application framework or CMS plugin

You usually want one primary redirect layer. Multiple layers can work, but they raise the chance of conflicts during migrations.

2. Status code behavior

Check that HTTP requests return the expected status code. For most public website migrations, a 301 is the normal choice because it tells browsers and crawlers the secure URL is the permanent version. For short-term testing, a 302 may be useful, but permanent redirects are generally cleaner once validated.

Test both:

  • http://example.com
  • http://www.example.com/path?query=test

Make sure path and query strings are preserved. A redirect that drops them can break search landing pages, API callbacks, or campaign links.

3. Canonical host behavior

HTTPS redirecting and host canonicalization are related but separate. Decide whether your preferred URL is:

  • https://example.com
  • https://www.example.com

Then verify the full chain is clean. Ideal behavior is a single hop when possible. For example, http://www.example.com/page should redirect directly to the final canonical HTTPS URL, not pass through several intermediate steps.

4. Proxy header correctness

If your app or origin sits behind a proxy, verify it sees the original scheme correctly. This matters for login flows, generated absolute URLs, secure cookies, and internal redirect rules. When these headers are wrong or untrusted, the classic result is a redirect loop HTTPS fix scenario.

5. Mixed content after redirect

A redirect only changes the page URL. It does not automatically fix insecure asset references. After forcing HTTPS, review browser console warnings and page source for hard-coded http:// links to scripts, images, stylesheets, fonts, or API endpoints. For a deeper troubleshooting guide, see Mixed Content Errors After Installing Let's Encrypt: Causes and Fixes.

6. Certificate coverage and renewal

Make sure all redirected hostnames are covered by a valid certificate. If you redirect both apex and www, both names should be included where needed. Also verify renewal automation rather than assuming it works. Useful references include How to Renew Let's Encrypt Certificates Automatically and Verify It Actually Works and Let's Encrypt Expiry Monitoring: Best Tools, Alerts, and Dashboard Options.

7. Health checks and internal endpoints

Some environments use plain HTTP for internal health checks or legacy integrations. If you force HTTPS globally, verify whether your platform expects a 200 over HTTP on a private path. In some cases, you may need a narrow exception for a load balancer health endpoint, but keep exceptions small and documented.

8. Application-level URL settings

Many content management systems and frameworks have their own site URL settings, trusted proxy options, or HTTPS middleware. Track changes there after plugin updates, framework upgrades, or environment variable changes. WordPress in particular can behave unpredictably if the site URL, reverse proxy headers, and web server redirects disagree. If that is relevant to your stack, see Let's Encrypt for WordPress: Hosting Requirements, Plugin Options, and HTTPS Fixes.

9. HSTS status

If you use HSTS, track its current max-age and whether subdomains are included. HSTS is valuable, but it should come after stable redirecting and valid certificates. If certificates lapse or subdomains are not consistently covered, HSTS can magnify the blast radius of a misconfiguration.

Cadence and checkpoints

The easiest way to keep redirects healthy is to treat them like a recurring operational check instead of a one-time setup task. A monthly or quarterly review is enough for most small sites, with extra checks after infrastructure changes.

Monthly checks

  • Request the homepage over HTTP and confirm a single permanent redirect to HTTPS.
  • Test one deep URL with a query string and confirm path preservation.
  • Check certificate expiry dates and recent renewal logs.
  • Review browser console output for mixed content on a representative page.
  • Confirm the preferred canonical host still resolves in one redirect step.

Quarterly checks

  • Audit where redirect logic exists across CDN, load balancer, server, and app.
  • Verify trusted proxy settings after platform or framework updates.
  • Review HSTS configuration and confirm it still matches certificate coverage.
  • Check non-browser flows such as webhooks, OAuth callbacks, payment return URLs, and API clients.
  • Retest staging-to-production differences if you maintain separate environments.

Change-driven checkpoints

Revisit redirects immediately after any of the following:

  • DNS provider or CDN changes
  • Migration from shared hosting to VPS or cloud hosting
  • Nginx, Apache, or ingress config edits
  • Certificate automation changes, including switching ACME clients
  • New reverse proxy, WAF, or load balancer deployment
  • Application upgrades that alter trusted proxy or URL handling

If you are evaluating hosting environments that make TLS and redirect handling easier, see Best Hosting for Let's Encrypt Support: Shared, VPS, Cloud, and Managed Options.

A simple command-line test is often enough for routine checks:

curl -I http://example.com/path?x=1

Look for the redirect status and the Location header. Then test the final HTTPS URL directly to confirm it returns a normal success response and not another redirect loop.

How to interpret changes

When redirect behavior changes, the symptoms usually tell you where the problem lives. The key is to read them in context rather than chasing the first visible error.

If you see a redirect loop

A loop often means two layers disagree about whether the request is already secure. Common causes include:

  • The CDN forces HTTPS, but the origin redirects again because it thinks the request arrived over HTTP.
  • The app does not trust proxy headers and keeps enforcing HTTPS repeatedly.
  • A plugin or framework middleware duplicates server-level redirect rules.

To fix this, identify the first device that terminates TLS and ensure downstream systems understand the original protocol through trusted headers. Then remove redundant redirect logic where possible.

If only some pages break after redirecting

This points more often to mixed content, hard-coded URLs, or application-level asset generation rather than the redirect itself. Check browser developer tools, templates, CSS references, JavaScript endpoints, and CMS settings. The page may be redirecting correctly while loading insecure resources afterward.

If search or analytics data looks messy

Long redirect chains, inconsistent host canonicalization, or path-dropping rewrites may be the issue. Consolidate to one preferred host and one redirect hop where practical. Preserve request URIs and query strings unless you have a very specific reason not to.

If certificates renew but users still report warnings

Check whether every hostname involved in redirects is covered. It is common to renew the main hostname while forgetting www, a legacy subdomain, or a staging name that is still exposed. Also verify the certificate actually deployed to the live listener after renewal, especially behind load balancers or on clustered systems.

If health checks begin to fail

Look for an infrastructure expectation mismatch. Some platforms follow redirects cleanly; others expect a direct 200 on a fixed path. The right answer is rarely to weaken HTTPS across the whole site. A narrow exception on an internal-only path is usually safer than broad relaxation.

If you are using Let's Encrypt automation and want alternatives to the default client, see Certbot Alternatives for 2026: When to Use acme.sh, Dehydrated, Win-ACME, or Caddy. If you are deciding whether free certificates are sufficient for your environment, see Let's Encrypt vs Paid SSL Certificates: When Free Is Enough and When It Isn't.

When to revisit

Use this section as your practical maintenance checklist. You should revisit your HTTPS redirect setup on a schedule and after any meaningful platform change, even if the site appears fine at first glance.

Revisit monthly if your site is customer-facing, integrates with external services, or has changed recently. Revisit quarterly if the stack is stable and low-change. Review immediately after any migration, CDN adjustment, certificate method change, or reverse proxy update.

Here is a compact action list worth repeating:

  1. Run an HTTP request against the main hostname and a deep URL.
  2. Confirm the response is a 301 to the correct HTTPS destination.
  3. Verify there is no multi-hop chain unless deliberately required.
  4. Open the final HTTPS page in a browser and check for mixed content.
  5. Confirm your app generates HTTPS absolute URLs and secure cookies.
  6. Review certificate validity for all relevant hostnames.
  7. Check renewal automation logs and alerting.
  8. Audit whether redirect logic now exists in more than one layer.
  9. Test one external integration flow such as login, webhook, or callback.
  10. Only then review HSTS and other hardening headers.

If you want this article’s most important takeaway in one line, it is this: put the redirect in the right layer, keep it singular where possible, and re-test whenever certificates, proxies, DNS, or application URL handling changes.

That approach keeps a simple force HTTPS redirect simple over time. It also makes your setup easier to reason about when the inevitable change arrives: a hosting migration, a new CDN rule, a framework upgrade, or a certificate renewal problem that surfaces at the least convenient moment.

Related Topics

#https-redirect#nginx#apache#cdn#best-practices
A

Alex Rowan

Senior SEO Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.