ScreenshotNeo

BlogHow-to

How to Redirect a Website from HTTP to HTTPS

Configure HTTPS first, then redirect HTTP requests while preserving the hostname, path, and query string. Learn 301 vs. 308, Apache and NGINX setup, HSTS, and troubleshooting.

By the ScreenshotNeo team30 September 20269 min read

How to Redirect a Website from HTTP to HTTPS

To redirect a website from HTTP to HTTPS, first configure HTTPS with a valid TLS certificate and confirm that your site works at its HTTPS address. Then keep an HTTP listener on port 80 and return a permanent redirect to the same hostname, path, and query string over HTTPS. For ordinary website pages, use status 301. Use 308 when a permanent redirect must preserve a request method and body, such as for an API endpoint.

A redirect does not provide encryption by itself: the destination must already complete a valid TLS connection. After the redirect works, you can add HSTS so browsers that have received the policy upgrade later HTTP attempts automatically.

1. Prepare HTTPS before redirecting

Start by obtaining and installing a certificate for every hostname visitors use, such as the apex domain and www subdomain. Protect the private key. NGINX requires that its master process can read the key, and the key should be treated as a secure credential. [NGINX HTTPS server configuration]

Before changing port 80, visit the HTTPS version of the site directly. Check the pages, static assets, redirects, cookies, and canonical hostname. If HTTPS is broken, an HTTP redirect will send visitors to a broken destination.

  1. Install and verify the certificate and private key.
  2. Configure the HTTPS virtual host or server block for the intended hostname.
  3. Confirm representative pages and assets load at https://.
  4. Check that your certificate renewal process can still complete challenges. ACME clients such as Certbot may need plain HTTP access to /.well-known/acme-challenge/. [Apache URL remapping and rewrite guide]

2. Choose the redirect status

Status Use it for Behavior
301 Moved Permanently Normal website navigation and pages Permanent redirect. GET remains GET, but user agents may change other methods.
308 Permanent Redirect Permanent redirects where method and body must remain intact Preserves the request method and body, useful for API operations.

For a typical site, 301 is the conventional choice. If a client sends a POST or PUT request and must repeat that same operation at the HTTPS URL, choose 308 and verify the behavior with the clients you support. MDN documents the method behavior and redirect semantics for 301 and 308.

Permanent redirects can be cached by browsers and intermediaries. During initial configuration, test with temporary redirects if your deployment process allows it; then change to the permanent status once the destination and hostname policy are correct. Do not leave an unintended cached redirect pointing at the wrong host.

3. Configure NGINX

Use a dedicated port 80 server block. The following redirects every request to HTTPS on the same hostname and preserves the full request URI, including its path and query string:

A correct redirect keeps the requested destination while switching the connection to HTTPS.
A correct redirect keeps the requested destination while switching the connection to HTTPS.
server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;

    # Leave this reachable if your ACME setup serves challenges over HTTP.
    location ^~ /.well-known/acme-challenge/ {
        root /var/www/acme;
    }

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

Replace the hostnames and challenge directory with your own. The $host variable carries the requested hostname; $request_uri includes the path and query string. If you want all visitors on one canonical hostname, make that choice deliberately. For example, a separate redirect from www.example.com to example.com may introduce a second hop if it is not planned into the first redirect.

For an API that must preserve methods and bodies, use 308:

location /api/ {
    return 308 https://$host$request_uri;
}

Keep the ACME exception only if your certificate automation needs it. If challenges are handled by another process or through DNS validation, follow that setup’s requirements. After editing, validate the configuration and reload NGINX according to your operating procedure.

4. Configure Apache

For Apache, a simple virtual-host redirect is often easier to reason about than a rewrite rule. Ensure this port 80 virtual host applies to the intended hostnames:

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

    # Preserve HTTP access for an ACME webroot challenge if required.
    Alias /.well-known/acme-challenge/ /var/www/acme/.well-known/acme-challenge/
    <Directory "/var/www/acme/.well-known/acme-challenge/">
        Require all granted
    </Directory>

    Redirect permanent / https://example.com/
</VirtualHost>

This version sends both configured hostnames to https://example.com/. Apache’s Redirect permanent carries the path after the matched prefix to the destination. If you want to preserve each requested hostname instead, or have more complex routing, use a carefully scoped rewrite rule and test its output.

Apache documents this mod_rewrite pattern for HTTPS redirection:

RewriteEngine On
RewriteRule "^(.*)" "https://%{SERVER_NAME}$1" [R=301,L]

That rule can be placed in the appropriate port 80 virtual host or directory context. Be careful with directory-level rules: path prefixes and rewrite bases affect the resulting URL. See the Apache rewrite documentation and validate the final Location header rather than assuming the rule produced the intended path.

5. Configure a managed edge or hosting panel

If a CDN, load balancer, or hosting control panel terminates TLS, configure the HTTP-to-HTTPS redirect at the layer that receives public traffic. Confirm that it can preserve the host, path, and query string, and check whether the origin separately handles HTTP. Avoid enabling competing redirects at the edge and origin until you know how they interact; duplicate or conflicting rules can create loops or extra hops.

When a reverse proxy sits in front of Apache or NGINX, the application server may see an internal HTTP connection even though the public visitor used HTTPS. Configure trusted proxy headers and application URL generation correctly. A misconfigured app can otherwise redirect HTTPS requests back to HTTPS repeatedly, or generate insecure asset links.

6. Test redirects and the final page

Use curl -I to inspect the first response. This makes a HEAD request and shows the status and response headers:

curl -I 'http://example.com/products/item?ref=campaign'

Expect a permanent redirect and a Location header with the HTTPS scheme and expected host, path, and query string. Then request the destination directly:

curl -I 'https://example.com/products/item?ref=campaign'

For a GET request and its complete response chain, use:

curl -sS -L -D - -o /dev/null 'http://example.com/products/item?ref=campaign'

Check that the redirect chain ends successfully and has no unnecessary hops. Use browser developer tools to look for mixed-content warnings: a page can load over HTTPS while requesting scripts, stylesheets, images, or API resources over HTTP.

  • Test the apex and www hostnames.
  • Test a URL with a path, trailing slash, and query string.
  • Test an unknown path to ensure it is preserved rather than redirected to the homepage.
  • For APIs, test POST or PUT behavior and confirm whether the client follows the redirect with the same method and body.
  • Test the ACME challenge path if certificate issuance or renewal uses HTTP validation.
  • Check cookies, secure session behavior, canonical links, and mixed content.

7. Add HSTS after HTTPS is stable

HTTP Strict Transport Security (HSTS) tells a browser that has received the policy over HTTPS to use HTTPS for future connections to that host. Browsers ignore HSTS headers sent over HTTP, and HSTS does not protect the first connection before the browser has received an HTTPS response containing the policy. [MDN: Strict-Transport-Security]

HSTS helps a browser upgrade future requests after it has received the policy over HTTPS.
HSTS helps a browser upgrade future requests after it has received the policy over HTTPS.

Send the header only on HTTPS responses. A typical starting policy is:

Strict-Transport-Security: max-age=31536000

Once you have verified that every subdomain supports HTTPS, you can consider including them:

Strict-Transport-Security: max-age=31536000; includeSubDomains

Do not add includeSubDomains until you have checked all subdomains, including services that are rarely used or managed by another team. A browser that remembers the policy will refuse insecure HTTP access to covered hosts for the stated period. HSTS is a policy commitment, not a substitute for certificates, correct redirects, or testing.

8. Common problems and fixes

Symptom Likely cause Fix
Browser reports a certificate error after redirect HTTPS host lacks a valid certificate, or certificate does not cover the requested hostname Install a valid certificate for each public hostname and verify the HTTPS virtual host before redirecting.
Too many redirects Edge, origin, or application rules disagree about scheme or canonical host; proxy scheme information may be wrong Inspect each Location in the chain, keep one clear canonical policy, and configure trusted proxy scheme handling.
Path or query disappears Redirect target is fixed to the homepage or rewrite syntax drops the original URI Preserve the request URI in NGINX or use an Apache redirect mapping that carries the suffix. Confirm with a non-root URL.
POST changes to GET Some clients change methods when following a 301 Use 308 when preserving method and body is required, and verify client behavior.
Certificate renewal fails The HTTP challenge path is redirected, blocked, or routed away from the ACME client Keep the required /.well-known/acme-challenge/ route available or use the validation method configured for your certificate automation.
HTTPS page has missing or blocked assets Asset URLs are hard-coded as HTTP, producing mixed content Update asset URLs and application configuration to HTTPS, then inspect the browser console and network panel.
Redirect loop only behind a proxy The origin thinks the public HTTPS request is HTTP Configure the application to trust scheme information from the known proxy and avoid trusting arbitrary client-supplied headers.

9. Reliability, performance, and cost

A redirect adds a request and response before the browser fetches the HTTPS page, so a direct HTTPS link avoids that extra round trip. Keep internal links, canonical URLs, sitemaps, and asset references on HTTPS to reduce repeat redirects. For a newly migrated site, preserve the old paths and query behavior so bookmarks and external links continue to reach the intended content.

Reliability depends on the certificate being valid and renewed, the redirect listener staying available, and every relevant hostname resolving to the right edge or server. Monitor certificate renewal and test representative URLs after configuration changes. There is no universal performance or cost figure: hosting, traffic, TLS termination, certificate management, and any CDN or load balancer depend on your deployment.

Certificate provisioning and edge redirect controls may be available through managed hosting, a CDN, or a TLS provider. Choose based on whether you need the provider to issue and renew certificates, terminate TLS, and manage redirects for your hostnames. Keep control of the hostname policy and renewal path whichever platform you use.

10. Inspect the finished page with ScreenshotNeo

After HTTPS works, inspect the page visually to catch layout issues, missing assets, and overlays that may not be obvious from response headers. ScreenshotNeo is a website screenshot API and MCP server for developers. Here is its one-request screenshot call; see the API documentation for the available options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp

Python:

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://example.com"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://example.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
const bytes = new Uint8Array(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', bytes));

ScreenshotNeo accepts cookie and consent banners like a visitor, then removes more than 60 known consent platforms, newsletter popups, and chat widgets before the capture; you can turn each step off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers say which page verdict applied and whether the request was billed. Its MCP server gives AI agents tools for screenshots, page information, and PDF capture.

The free plan includes 1,000 screenshots a month with no card. Paid plans start at $5 for 3,000 shots; higher plans are Growth at $15 for 15,000, Pro at $39 for 60,000, Scale at $99 for 250,000, and Business at $249 for 1,000,000. Yearly billing gives two months free, and every feature is on every plan. Sign up for 1,000 free screenshots a month, with no card.

FAQ

Should I redirect HTTP to HTTPS on every page?

Usually, yes. Redirect each requested path to its HTTPS equivalent so existing links and bookmarks continue to work. Avoid sending every URL to the homepage.

Does HSTS replace the HTTP redirect?

No. The redirect handles a request that arrives over HTTP. HSTS helps browsers that have already received the policy over HTTPS upgrade later requests.

Can I redirect HTTP to HTTPS before installing a certificate?

You can configure the redirect, but visitors cannot use the destination until HTTPS serves a valid certificate for the hostname. Set up and verify TLS first.

Is a 301 redirect enough for an API?

It depends on the operation and client. If the request method and body must be preserved, use 308 and test with the clients that call the API.

No. It redirects page requests. Update insecure asset and application URLs, then check the browser for mixed-content errors.