Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk10 min

How to Force HTTPS Using .htaccess (Apache HTTP Server)

Add this Apache .htaccess rule to redirect HTTP to HTTPS, then validate modules, overrides, proxy behavior, mixed content and optional HSTS settings.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Put the following three-line block in the .htaccess file inside your site’s document root (or another directory where overrides are enabled):

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

It redirects every HTTP request to the equivalent HTTPS URL with a permanent (301) response. The rule works only when Apache has mod_rewrite loaded and the relevant directory permits .htaccess overrides. If TLS ends at a reverse proxy or load balancer, use the proxy’s documented forwarded-protocol signal instead of relying on %{HTTPS}.

As an Amazon Associate I earn from qualifying purchases.

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.

What forcing HTTPS does

HTTP and HTTPS are separate URL schemes. An HTTP request can reach your server even when the site has a valid TLS certificate, so installing a certificate alone does not force visitors onto encrypted connections. A redirect makes Apache answer the HTTP request with a new HTTPS location; the browser then requests that secure URL.

The rule below is a per-directory mod_rewrite rule. It checks whether Apache considers the current request secure. If not, it returns a permanent redirect and stops processing additional rewrite rules for that request.

#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter | 4Pack Type C Female to A Male Cable Converter for Apple Duo 17 16 15 14 Plus,iWatch Watch 12 11 10,iPad 9 8 Air,Airpods 5 4
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
RewriteEngine On
RewriteCond "%{HTTPS}" !=on
RewriteRule "^(.*)" "https://%{SERVER_NAME}$1" [R=301,L]

What each line means

  • RewriteEngine On enables rewrite processing in this directory.
  • RewriteCond "%{HTTPS}" !=on allows the redirect only when the HTTPS environment variable is not on. An already-secure request therefore passes through without being redirected again.
  • RewriteRule "^(.*)" "https://%{SERVER_NAME}$1" [R=301,L] matches the requested path, prefixes it with HTTPS and the server name, and sends a 301 response. R=301 marks the redirect as permanent; L means this is the last rewrite rule for the current pass.

The path captured by (.*) is appended after the host, so a request such as http://example.test/account/settings is redirected to the corresponding HTTPS path rather than merely to the home page. Query strings are normally retained by Apache when a rewrite does not supply a replacement query string.

Prerequisites before editing .htaccess

Apache must have mod_rewrite loaded

The directives are provided by Apache’s mod_rewrite module. If the module is unavailable, Apache will reject the file with an “Invalid command” or similar configuration error. Check the module state using your hosting control panel or your administrator’s module list before deploying the rule.

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.

The directory must allow overrides

Apache reads .htaccess files only when the relevant Directory configuration permits overrides. Apache’s documentation guidance cited for this method uses AllowOverride All in the applicable directory block. A host may intentionally allow only selected override classes, so a file can exist and still be ignored or refused. If you control the server, inspect the Directory block that covers the document root; on managed hosting, ask the provider whether rewrite directives are enabled.

HTTPS itself must already work

Install and configure the certificate and HTTPS virtual host first. Test an HTTPS URL directly before adding a redirect. A redirect cannot repair an incorrect certificate, an unopened TLS port, a virtual-host mismatch or an application that fails when reached over HTTPS.

Back up the current file

Preserve the existing .htaccess before changing it. Rewrite files often contain front-controller, caching, authentication or asset rules. Add the HTTPS block in a deliberate location and keep unrelated rules intact; a misplaced rule can alter application routing.

How to add the rule safely

  1. Open the .htaccess file in the site’s document root, or create one there if your host permits it.
  2. Insert the three-line block shown above. Keep the directives outside another directive’s block unless your existing configuration specifically requires a different context.
  3. Save the file as plain text named exactly .htaccess. Do not append .txt, and do not put it in a parent directory that does not contain the site.
  4. Request an HTTP URL that includes a real path, such as http://example.test/contact. Confirm that the response is a 301 and that its Location points to the same path under https://.
  5. Follow the HTTPS destination in a browser and verify that the page, forms, stylesheets, scripts and images load without mixed-content warnings.
  6. Test an HTTPS URL directly. It should return the page without redirecting back to HTTP.

For a header-only check, a command such as curl -I http://example.test/contact displays the status and response headers without downloading the page. Replace the example host and path with your own URL. Test several paths, not just the home page, because application and directory rules can behave differently.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter | USB C Dongle with 90W Max Power Delivery, 3×5Gbps USB A Data Ports, for MacBook, Dell, and More (Charger Not Included)
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Understanding the 301 redirect

A 301 tells clients and search engines that the move is permanent. Search engines can update indexed URLs to the HTTPS versions, while browsers and intermediaries may cache the redirect. That cacheability is useful after a confirmed migration but makes mistakes inconvenient to undo.

During initial troubleshooting, you can temporarily use a non-permanent redirect while checking behavior, but the published rule uses R=301 for the intended permanent policy. Once a browser has cached a 301, test with a private window, a different browser or a command-line client when verifying a correction.

Where the redirect should live: .htaccess or the HTTP virtual host

Apache’s 2.4 rewrite documentation describes HTTPS redirection as a common use of mod_rewrite but says it is usually better handled without mod_rewrite. When you have server or virtual-host access, put a dedicated redirect in the HTTP virtual host using Apache’s Redirect directive. That server-level approach is parsed with the rest of the virtual-host configuration and avoids the per-request directory walk required for .htaccess.

Method Where it lives Operational advantage Typical dependency or failure
.htaccess with mod_rewrite Per-directory file beneath the document root Can be deployed by a site administrator without editing the main Apache configuration or restarting the service Requires mod_rewrite and an AllowOverride policy that permits the directives; a misplaced or ignored file has no effect
Server-level Redirect Dedicated HTTP virtual host Apache’s preferred, simpler location when you control the server; configuration is centralized and can be reloaded deliberately Requires root or virtual-host access and correct HTTP virtual-host matching; changes normally require a configuration reload

Both methods still need a correctly configured HTTPS virtual host. If TLS terminates before the request reaches Apache, both methods also need a condition that reflects the proxy’s protocol handling.

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

Preventing redirect loops behind a proxy or load balancer

The three-line block assumes Apache itself negotiated TLS. In a reverse-proxy or load-balancer architecture, the client may use HTTPS to the proxy while the proxy forwards plain HTTP to Apache. In that arrangement, mod_ssl is not handling the backend connection and %{HTTPS} can remain off for every request. Apache then redirects even requests that were already secure at the public edge, producing a loop.

How to correct the condition

  1. Determine where TLS terminates: the web server, a load balancer, a CDN or another reverse proxy.
  2. Read the proxy’s documentation to identify the forwarded-protocol header it sets and the exact value used for HTTPS.
  3. Change the redirect condition so Apache trusts that documented signal, rather than %{HTTPS}, when the request came through the trusted proxy.
  4. Ensure untrusted clients cannot set the same header directly. The proxy should overwrite or sanitize it before forwarding requests.
  5. Test both public HTTPS and public HTTP URLs from outside the network. A successful test must show one redirect from HTTP and a normal 200-level response for HTTPS.

The exact header name is deployment-specific and is not safe to guess. Use the name, value and trust model supplied by your proxy or hosting provider. If you cannot verify those details, ask the provider to implement the redirect at the edge or in the HTTPS-aware virtual host.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter | 85W Max PD, 2 USB 3.0 & 1 USBC Data Ports, SD/TF Card Reader, for Laptops/Mac and Other Type C Devices (Charger Not Included)
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Interactions with existing rewrite rules

Many applications already use mod_rewrite to send all requests to an entry script, remove a front-controller filename or normalize trailing slashes. The HTTPS block should run in an order that does not create a second redirect or discard the original path.

Symptoms of an ordering problem

  • Multiple redirect hops: HTTP changes to HTTPS, then the application redirects again for a slash, host name or canonical path. Combine compatible policies where possible and check each Location response.
  • A loop between HTTP and HTTPS: Apache’s secure-state test is false on requests that arrived through a proxy. Fix the proxy condition described above.
  • A 404 after redirection: The HTTPS virtual host may point to a different document root, or another rewrite rule may be matching a path differently there.
  • The rule appears ignored: The file may be outside the active document root, overrides may be disabled, or mod_rewrite may not be loaded.
  • An internal application redirect returns to HTTP: Update the application’s base URL or canonical URL setting after HTTPS is functioning. The server redirect cannot prevent an application from emitting an insecure absolute URL.

Review Apache’s error log after each configuration change. Syntax errors generally prevent the virtual host from loading, while logical errors show up as unexpected status codes, paths or repeated redirects.

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

Mixed content after the redirect

Redirecting the document does not automatically change absolute HTTP links embedded in HTML, CSS, JavaScript, feeds or database content. Browsers may block active mixed content such as scripts and may warn about passive content such as images.

  • Inspect the browser’s developer console for the first insecure resource.
  • Change hard-coded http:// URLs to HTTPS URLs where the destination supports TLS.
  • Update application configuration, media URLs, canonical tags, sitemaps and API endpoints.
  • Check third-party widgets and fonts; a resource provider that lacks HTTPS must be replaced or removed.

Do not use the redirect rule as a substitute for correcting resource URLs. The page can be securely delivered while its dependencies still fail or expose visitors to downgrade warnings.

Adding HSTS after HTTPS is proven

HTTP Strict Transport Security (HSTS) is separate from the redirect. A browser that receives HSTS over HTTPS remembers to use HTTPS for future requests, including before it makes an initial HTTP request.

Enable the headers module

On Debian- or Ubuntu-style Apache installations, the documented module-enabling command is:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray | Data transfer & Fast charging for MacBook, iPhone 17/16/15, iPad, Samsung Galaxy, Apple Watch
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
sudo a2enmod headers

Reload or restart Apache using your operating system’s normal service procedure after enabling the module, and verify that the configuration remains valid.

Set HSTS only on the HTTPS virtual host

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

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

The always keyword makes Apache add the header on all responses, including error responses. HSTS has no useful effect when delivered over an insecure HTTP response.

Increase the policy gradually

Begin with a short max-age while you confirm that every required hostname and subdomain works over HTTPS. Raise the value only after you have checked redirects, APIs, administrative paths, monitoring endpoints and third-party integrations. The example value, 31536000, represents one year; use it only when you are prepared for browsers to enforce that duration.

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

Treat includeSubDomains and preload as advanced choices

includeSubDomains extends the policy to subordinate hostnames. Do not enable it until every relevant subdomain is HTTPS-capable, including ones that are rarely visited or operated by another team.

The preload directive is more consequential: submitting a domain to browser preload lists can make HTTPS enforcement persist beyond the header’s lifetime and is difficult to reverse quickly. It is not a default requirement for forcing HTTPS and should be considered only after a deliberate audit of the entire domain.

Best Value
Sale
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display | 85W Max PD, 1 Powered USB-C 5Gbps & 2 Powered USB-A 3.0 5Gbps Data Ports, for MacBook Pro, MacBook Air, Dell and More (Black)
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Validation checklist

  • HTTPS opens without certificate, hostname or protocol errors.
  • An HTTP request returns exactly the intended permanent redirect.
  • The redirect preserves the requested path and does not unexpectedly change the host.
  • An HTTPS request does not redirect back to HTTP.
  • Several paths, query strings, login flows and form submissions behave correctly.
  • There is no redirect loop when traffic passes through the production proxy or load balancer.
  • Stylesheets, scripts, images, fonts, APIs, canonical tags and sitemaps use HTTPS.
  • Apache’s error log is clear of rewrite syntax errors.
  • Search-engine and analytics settings use the HTTPS property or URL where applicable.
  • HSTS is added only after the secure site has been tested across all required subdomains.

When not to use this exact block

The site is behind TLS termination

Use the forwarded-protocol condition supplied by the trusted proxy instead. Applying the basic %{HTTPS} test unchanged can loop indefinitely.

You control the Apache virtual host

Prefer a dedicated server-level Redirect in the HTTP virtual host, as Apache’s documentation recommends in most cases. Keep .htaccess for environments where changing the main configuration is not possible.

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

The site has a nonstandard canonical host

The supplied rule uses %{SERVER_NAME}. If your public policy also requires selecting one host name (for example, one of several aliases), define and test that host policy separately so that HTTPS enforcement and host canonicalization do not produce competing redirects.

Common questions

Will this redirect HTTPS requests again?

No. When Apache sees %{HTTPS} as on, the condition is false and the redirect rule is skipped. A proxy that hides the original protocol is the important exception.

Does a 301 redirect change my certificate?

No. The certificate and TLS virtual host must already be valid. The redirect only tells an HTTP client which HTTPS URL to request.

Can I put the file in any directory?

Only if that directory is within the request path and Apache allows overrides there. For a site-wide policy, place it in the document root covered by the active virtual host.

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

Should I enable HSTS at the same time?

No. HSTS is optional and separate. First verify that HTTPS, redirects, subdomains and application integrations work; then add the header on the HTTPS virtual host and increase max-age cautiously.

Final recommendation

For a host that supports .htaccess, use the documented three-line mod_rewrite block, verify one-hop HTTP-to-HTTPS redirects across real site paths, and investigate proxy termination before diagnosing a loop. If you administer Apache’s virtual hosts, implement the permanent redirect at server level instead. Add HSTS only after the HTTPS deployment is dependable, starting with a short lifetime and treating subdomain coverage and preload as deliberate, high-impact decisions.

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.

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 from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

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.