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.
Antihost offers managed WordPress hosting with free migration, one-click staging and a 14-day free trial.
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:
| # | Preview | Product | Price | |
|---|---|---|---|---|
| 1 |
|
Apache HTTP Server 2.4 Reference Manual 1/3 | $29.99 | Buy on Amazon |
| 2 |
|
Apache HTTP Server Reference Manual - For Apache Version 2.2.17 | $17.61 | Buy on Amazon |
| 3 |
|
Apache HTTP Server Documentation Version 2.5 | $49.95 | Buy on Amazon |
| 4 |
|
Apache HTTP Server 2.2 Official Documentation - Volume III. Modules (A-H) | $984.26 | Buy on Amazon |
| 5 |
|
Apache HTTP Server. | $14.09 | Buy on Amazon |
As an Amazon Associate I earn from qualifying purchases.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →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.
#1 Best Overall
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.
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
- Back up the existing file. Download or copy the current
.htaccessbefore editing it. Existing rewrite rules may handle front-controller routing, access controls, or cached assets. - 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.
- Check the module and override settings. Confirm that
mod_rewriteis loaded and that the directory permits the rewrite directives. If you cannot inspect the virtual-host configuration, ask the host for these two confirmations. - 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. - Save without changing the syntax. Keep the quotes, condition operator, substitution, and flags as shown. The
R=301flag makes the redirect permanent;Ltells the current rewrite pass to stop after this rule. - 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. - 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.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errorsRewriteCond "%{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.
Rank #2
- Used Book in Good Condition
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.
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.
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.
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.
Rank #4
- Used Book in Good Condition
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.
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.
Recommended Free Tools
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
AllowOverridepolicy prevents the file from taking effect. - Confirm that
mod_rewriteis 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.Deployment checklist
- HTTPS works directly for the site’s main pages and important deep links.
- A backup of the current
.htaccessexists. mod_rewriteis 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.
Best Value
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.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →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.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchShould 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
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.




