October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
Blog

How to Force HTTPS Using .htaccess (Apache 2.4)

Use this Apache .htaccess rule to redirect HTTP requests to HTTPS, then verify overrides, proxy behavior, and optional HSTS settings.
Length11 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Put the three-line mod_rewrite rule below in the site’s document-root .htaccess file, after confirming that Apache allows overrides and that mod_rewrite is loaded. It permanently redirects requests whose connection is not HTTPS.

The .htaccess rule that redirects HTTP to HTTPS

Use this block in the site’s document root, or in the relevant Apache directory where overrides are enabled:

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
RewriteEngine On
RewriteCond "%{HTTPS}" !=on
RewriteRule "^(.*)" "https://%{SERVER_NAME}$1" [R=301,L]

The rule applies to requests for which Apache reports HTTPS as anything other than on. Those requests receive a permanent redirect to the HTTPS version of the requested path. Requests that are already HTTPS do not match the condition and continue normally.

A redirect is not the same as serving the page over encryption. Your HTTPS virtual host, certificate, and application must already work before you make the HTTP-to-HTTPS redirect permanent. Test the HTTPS URL directly first, then enable this rule.

Requirements to check before editing .htaccess

Apache must have mod_rewrite loaded

The directives in the block belong to Apache’s mod_rewrite module. If that module is unavailable, Apache will reject the directives or ignore the intended redirect, depending on the server’s configuration. Confirm module availability with the administrator or hosting control panel before saving the file.

Overrides must be allowed for the directory

Apache reads .htaccess on each request only when the relevant directory configuration permits overrides. The Apache guidance summarized for this setup identifies AllowOverride All in the applicable Directory block as the usual requirement. A host may permit only selected override classes instead, so use the setting provided by your administrator rather than changing a server-wide policy blindly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If overrides are disabled, the file can appear perfectly formatted while having no effect. In that case, place the redirect in the HTTP virtual-host configuration instead, or ask the host to enable the necessary override class.

HTTPS must be reachable first

Open the site’s HTTPS address and check the pages, assets, forms, and application routes that matter. Resolve certificate or virtual-host problems before adding a permanent redirect. Otherwise, visitors can be sent from a working HTTP address to an HTTPS endpoint that still fails.

How to add the rule safely

  1. Back up the existing file. Download or copy the current .htaccess before editing it. Existing rewrite rules may handle front-controller routing, access controls, or cached assets.
  2. Locate the correct directory. For a normal Apache site, this is the document-root directory that serves the public site. A rule in a subdirectory has a narrower scope and will not necessarily redirect requests handled elsewhere.
  3. Check the module and override settings. Confirm that mod_rewrite is loaded and that the directory permits the rewrite directives. If you cannot inspect the virtual-host configuration, ask the host for these two confirmations.
  4. Add the block. Place the three lines in the file. If another section already contains RewriteEngine On, keep one active declaration and add the condition and rule in the appropriate rewrite section rather than creating conflicting logic.
  5. Save without changing the syntax. Keep the quotes, condition operator, substitution, and flags as shown. The R=301 flag makes the redirect permanent; L tells the current rewrite pass to stop after this rule.
  6. Request an HTTP URL. Test the bare domain and at least one deep link over http://. The response should be a redirect to the corresponding HTTPS address, not the final page returned directly over HTTP.
  7. Check the HTTPS destination. Follow the redirect and verify that the final page loads, its internal links use HTTPS, and important assets and form submissions still work.

Do not add a second HTTP-to-HTTPS rule in another included file unless you know how the two configurations interact. Duplicate redirects can produce confusing chains and make later troubleshooting harder.

What each line does

RewriteEngine On

This enables the rewrite engine for the directory context. Without it, the following condition and rule are not evaluated.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

RewriteCond "%{HTTPS}" !=on

The condition examines Apache’s HTTPS variable. The rule is allowed to run only when that variable is not on. This guard prevents an HTTPS request from being redirected to HTTPS again.

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

The pattern captures the requested path, and the substitution places that path after the HTTPS scheme and Apache’s SERVER_NAME value. The permanent redirect status is 301. Search engines use that status as a signal to update their indexed URL, while browsers and intermediaries may cache the result according to their redirect handling.

The host value comes from Apache’s server configuration. If a site deliberately accepts several hostnames, review which hostname Apache exposes as SERVER_NAME before deploying the rule. Host canonicalization is a separate decision; this block is intended to change the scheme from HTTP to HTTPS.

Why a 301 redirect is used

R=301 communicates that the HTTP address has been replaced permanently by its HTTPS counterpart. That is the appropriate status when the site has made HTTPS the canonical transport and you want search engines to update their index.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Permanent redirects can be cached, so test the HTTPS site and the exact rewrite behavior before publishing the rule broadly. During a controlled rollout, keep the previous .htaccess backup and record the change so a configuration mistake can be reversed quickly.

The server-level method is cleaner when you have access

Apache’s rewrite documentation describes the redirect as a common use of mod_rewrite, but says that, in most cases, a dedicated HTTP virtual host should use a Redirect directive instead. That approach keeps the redirect in the server configuration, where Apache can process it without reading a per-directory file on every request.

Use the server-level method when you control the virtual-host configuration or have administrator assistance. It normally requires a configuration reload after the change. The .htaccess method is useful when you cannot edit the virtual host and the hosting provider permits overrides; it can be deployed without a server restart.

Whichever location you choose, define the redirect in the HTTP virtual host and leave the HTTPS virtual host to serve the secure content. Ensure the virtual host matches the intended hostname, especially on servers hosting multiple sites.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Reverse proxies and load balancers: avoid redirect loops

If TLS terminates at a load balancer or reverse proxy, the connection arriving at Apache may be plain HTTP even though the visitor connected with HTTPS. In that architecture, mod_ssl is not handling the client-side TLS connection, and %{HTTPS} can report off for every request.

The result is a loop: the proxy sends an HTTPS request to Apache, Apache believes it is HTTP, and the rule redirects the request to HTTPS again. The browser then repeats the cycle.

How to correct the condition

Use the forwarded-protocol header that your proxy or load balancer documents, rather than relying solely on %{HTTPS}. The exact header name and value format are provider-specific; verify them in that product’s documentation and make sure the proxy cannot be spoofed by untrusted clients. Adjust the rewrite condition so Apache recognizes a request that was HTTPS at the edge.

Test from outside the proxy after making the change. A successful result is one redirect at most, followed by a 200-level HTTPS response from the application. If the request still loops, inspect the protocol value that reaches Apache and the proxy’s rule for setting it.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Optional hardening with HSTS

HTTP Strict Transport Security (HSTS) is separate from the redirect. A redirect tells a client how to reach HTTPS; an HSTS response header tells a supporting browser to use HTTPS automatically for a period of time.

Enable the headers module

Apache must have mod_headers loaded. On Debian- or Ubuntu-style installations, the usual module command is:

sudo a2enmod headers

Reload Apache using the operating procedure for your distribution after enabling a module or changing the virtual-host configuration.

Send HSTS only from the HTTPS virtual host

Add the header to the HTTPS virtual host, not the HTTP virtual host:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"

The always keyword makes Apache attach the header to all responses, including error responses. The example specifies a one-year max-age and applies the policy to subdomains.

Increase the policy gradually

Start with a shorter max-age while you confirm that every required hostname and subdomain works over HTTPS. Raise the value only after the site is consistently reachable through HTTPS. A browser that has learned a long HSTS policy can continue enforcing HTTPS after you remove the header, so treat the duration as an operational commitment.

Treat preload as an advanced decision

The preload directive has lasting consequences because it involves submitting the domain to browser preload lists. Do not add it as a routine extension of the header. Consider it only after you understand the eligibility requirements and can keep HTTPS working for the domain and its subdomains.

.htaccess versus an HTTP virtual-host redirect

Characteristic .htaccess rule Dedicated HTTP virtual host
Where it lives Per-directory configuration, usually in the document root Server-level Apache virtual-host configuration
Access needed Works when the host permits the required overrides Requires administrator or virtual-host configuration access
Deployment Can take effect without restarting Apache Normally requires a configuration reload
Main dependency AllowOverride policy and mod_rewrite Correct virtual-host matching and a valid server configuration
Apache’s stated preference Fallback when server configuration is unavailable Preferred location for a simple HTTP redirect in most cases
Proxy or load-balancer behavior Must account for the protocol seen by Apache Must account for the protocol seen by Apache

The choice is primarily about control and configuration scope, not about changing the destination: both methods should send HTTP requests to the site’s HTTPS endpoint.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshooting common failures

Nothing redirects

  • Confirm that the file is in the directory serving the requested site.
  • Verify that overrides are enabled for that directory. A disabled AllowOverride policy prevents the file from taking effect.
  • Confirm that mod_rewrite is loaded and that Apache accepted the configuration.
  • Check that you are testing an HTTP URL and not an HTTPS bookmark.

Apache returns a 500 error

  • Restore the backup if the error began immediately after editing the file.
  • Check Apache’s error log for the exact directive or syntax problem.
  • Look for missing quotes, altered flags, or a conflict with another rewrite section.
  • Have the administrator validate the configuration before re-enabling the rule.

The browser reports too many redirects

  • Check whether TLS terminates at a proxy or load balancer. If it does, the condition based on %{HTTPS} may never see the original HTTPS state.
  • Inspect the forwarded protocol value supplied by the proxy and update the condition to use the documented value.
  • Look for a second redirect at the proxy, application, or virtual-host layer that sends traffic back to HTTP.

The redirect goes to the wrong hostname

  • Inspect the hostname Apache supplies as SERVER_NAME.
  • Check which virtual host matched the request and whether several aliases are configured.
  • Separate scheme enforcement from hostname canonicalization; add a deliberate hostname policy only after deciding which names should remain valid.

HTTPS loads but some resources fail

Open the affected page over HTTPS and inspect the failing resource URLs. The redirect rule changes the document request; it does not rewrite every absolute URL generated by your application, content-management system, stylesheet, script, or third-party integration. Update those sources to emit HTTPS URLs, then retest forms, scripts, images, and API calls.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Deployment checklist

  • HTTPS works directly for the site’s main pages and important deep links.
  • A backup of the current .htaccess exists.
  • mod_rewrite is loaded.
  • The target directory permits the required overrides.
  • The three-line rule is present with R=301,L.
  • An HTTP request redirects to the matching HTTPS address without a chain or loop.
  • The HTTPS page serves its assets and handles forms and application routes correctly.
  • If a proxy terminates TLS, the rewrite condition uses the proxy’s documented forwarded-protocol signal.
  • HSTS is added only after HTTPS is stable, from the HTTPS virtual host, with a deliberately chosen max-age.

Frequently asked questions

Can I put the rule in any .htaccess file?

It must be in a directory whose overrides are enabled and whose scope covers the requests you want to redirect. A document-root file is the usual choice for an entire site; a subdirectory file affects only that directory’s scope.

Does the rule need to be repeated for every page?

No. The captured path is appended to the HTTPS destination, so one rule handles the requests that reach the directory where it is active.

Should I use HSTS instead of a redirect?

No. HSTS is an optional browser policy and does not replace the HTTP-to-HTTPS redirect for clients that have not yet learned the policy. Configure the redirect first, then add HSTS from the HTTPS virtual host when the site is ready.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What if I cannot edit Apache’s main configuration?

Use the .htaccess method if the host has enabled the necessary overrides and loaded mod_rewrite. If overrides are disabled, the hosting administrator must place the redirect in the HTTP virtual host or change the directory policy.

Why does a proxy require a different test?

Apache evaluates the connection it receives, which may be HTTP after a proxy has terminated TLS. Verify the protocol information forwarded by that proxy and configure the condition around its documented signal rather than assuming %{HTTPS} reflects the visitor’s original connection.

Frequently Asked Questions

Can I put the rule in any .htaccess file?

It must be in a directory whose overrides are enabled and whose scope covers the requests you want to redirect. A document-root file is the usual choice for an entire site; a subdirectory file affects only that directory’s scope.

Does the rule need to be repeated for every page?

No. The captured path is appended to the HTTPS destination, so one rule handles the requests that reach the directory where it is active.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should I use HSTS instead of a redirect?

No. HSTS is an optional browser policy and does not replace the HTTP-to-HTTPS redirect for clients that have not yet learned the policy. Configure the redirect first, then add HSTS from the HTTPS virtual host when the site is ready.

What if I cannot edit Apache’s main configuration?

Use the .htaccess method if the host has enabled the necessary overrides and loaded mod_rewrite. If overrides are disabled, the hosting administrator must place the redirect in the HTTP virtual host or change the directory policy.

Why does a proxy require a different test?

Apache evaluates the connection it receives, which may be HTTP after a proxy has terminated TLS. Verify the protocol information forwarded by that proxy and configure the condition around its documented signal rather than assuming %{HTTPS} reflects the visitor’s original connection.

Quick Recap

Bestseller No. 2
Bestseller No. 4
Bestseller No. 5

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.