How to Redirect HTTP to HTTPS Using .htaccess
Jessica MooreShare
After installing an SSL Certificate on your website, one crucial step remains. You must configure your server to automatically redirect all visitors from the insecure HTTP version to the encrypted HTTPS version.
Without this redirect in place, visitors who type your domain directly or follow old links may still access the unprotected version of your site.
For websites running on Apache servers, the .htaccess file provides a straightforward method for implementing this redirect. This configuration file gives you precise control over how your server handles requests, allowing you to enforce HTTPS connections across your entire website or only on specific sections.
This guide explains what the .htaccess file is, how to locate and edit it safely, and provides the exact code needed to redirect HTTP traffic to HTTPS on your Apache server.
Why Redirecting HTTP to HTTPS Matters
Simply installing an SSL Certificate does not automatically force all visitors to use the secure connection. Without a redirect in place, your website remains accessible through both HTTP and HTTPS, creating several problems.
Visitors who access your site through HTTP see browser warnings indicating the connection is not secure. These warnings damage trust and may cause potential customers to leave immediately. Modern browsers display prominent "Not Secure" messages in the address bar for any page loaded over HTTP.
Search engines treat HTTP and HTTPS versions as separate websites, potentially splitting your ranking authority between two versions of the same content. This dilutes your SEO efforts and can result in duplicate content penalties.
Sensitive data transmitted over HTTP travels in plain text, vulnerable to interception by malicious actors. Login credentials, personal information, and payment details all require the encryption that only HTTPS provides.
Implementing a server-side redirect ensures every visitor automatically receives the secure version of your website, regardless of how they arrive or which links they follow.
Understanding the .htaccess Configuration File
The .htaccess file is a powerful configuration file used by Apache web servers. Its name stands for "hypertext access," and it allows website administrators to control server behaviour on a per-directory basis without modifying the main server configuration.
What .htaccess Controls
This configuration file influences how your Apache server responds to requests for files within its directory and all subdirectories below it. You can place multiple .htaccess files throughout your website structure, each controlling settings for its specific location.
Common uses for .htaccess include setting up redirects, rewriting URLs for cleaner addresses, controlling access to directories through password protection, setting custom error pages, and enabling or disabling specific server features.
The file processes directives, which are instructions that tell Apache how to behave. For HTTPS redirection, you primarily use the RewriteEngine directive along with RewriteCond and RewriteRule commands.
Why .htaccess Files Are Hidden
The filename begins with a dot, which marks it as a hidden file on Unix-based systems including Linux servers. This convention keeps configuration files out of normal directory listings, reducing the chance of accidental modification or deletion.
Most file managers and FTP clients hide dotfiles by default. You must specifically enable the option to view hidden files before the .htaccess file becomes visible in your directory listings.
File Location
The primary .htaccess file typically resides in your website's root directory, often called public_html, www, or htdocs depending on your hosting configuration. Changes made to this file affect your entire website.
You can also place .htaccess files in subdirectories to apply different rules to specific sections of your site. Rules in subdirectory files override those in parent directories for requests to files within that subdirectory.
Locating and Editing Your .htaccess File
Before making any changes, always create a backup of your existing .htaccess file. A syntax error in this file can make your entire website inaccessible, so having a backup allows quick recovery if something goes wrong.
Accessing Through cPanel File Manager
Most shared hosting accounts include cPanel, which provides a web-based file manager for editing files directly on your server. Log into your cPanel account and locate the File Manager icon in the Files section.
When File Manager opens, it displays your hosting account's directory structure. Navigate to your website's root directory, typically public_html for your primary domain.
By default, File Manager hides dotfiles including .htaccess. Click the Settings button in the upper right corner and enable the option labelled "Show Hidden Files" or "Show dotfiles." Click Save to apply this setting.
With hidden files visible, you should now see the .htaccess file in your root directory. Right-click on the file and select Edit or Code Edit from the context menu. If prompted about character encoding, accept the default UTF-8 setting and proceed.
The file opens in a text editor where you can add your redirect code. After making changes, click Save Changes to write the modifications to the server. Always test your website immediately after saving to confirm the changes work correctly.
Accessing Through FTP
File Transfer Protocol clients like FileZilla provide another method for accessing and editing your .htaccess file. Connect to your server using the FTP credentials provided by your hosting company.
Configure your FTP client to display hidden files. In FileZilla, navigate to Server in the menu bar and select Force showing hidden files. Other FTP clients have similar options in their settings or preferences menus.
Navigate to your website's root directory and locate the .htaccess file. You can either download the file to edit locally with a text editor like Notepad++ or use your FTP client's built-in editing feature if available.
After editing, upload the modified file back to your server, overwriting the existing version. Ensure your FTP client transfers the file in ASCII mode rather than binary mode to preserve line endings correctly.
Creating a New .htaccess File
If no .htaccess file exists in your root directory, you can create one. Using a plain text editor, create a new file and save it with the exact filename .htaccess including the leading dot and no file extension.
Some operating systems resist creating files that begin with a dot. In this case, save the file as htaccess.txt, upload it to your server, then rename it to .htaccess using your file manager or FTP client.
Redirect Code for Different Scenarios
The specific code you add to .htaccess depends on what portions of your website you want to redirect. Apache's mod_rewrite module handles these redirects, using conditional rules to determine when redirection should occur.
Redirecting All Website Traffic
The most common requirement is forcing HTTPS across your entire website. This ensures every page, image, and resource loads securely regardless of how visitors access your site.
Add the following code to your .htaccess file :
RewriteEngine On RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R=301,L]
Replace yourdomain.com with your actual domain name. The first line activates the rewrite engine. The second line checks whether the request arrived on port 80, which handles standard HTTP traffic. The third line redirects matching requests to the HTTPS version while preserving the requested path.
The R=301 flag indicates a permanent redirect, which tells browsers and search engines that this change is lasting. The L flag marks this as the last rule to process, preventing conflicts with subsequent rules.
Alternative Method Using HTTPS Variable
Another approach checks directly whether the connection uses HTTPS rather than examining the port number. This method works better in some hosting configurations :
RewriteEngine On RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R=301,L]
This code activates when the HTTPS variable equals "off," indicating an insecure connection. The result is identical to the port-based method, but some servers respond more reliably to this approach.
Redirecting a Specific Domain Only
When your hosting account contains multiple domains, you may want HTTPS redirection on only one of them. This selective approach avoids affecting other websites that may not yet have SSL Certificates installed.
Use the following code to target a specific domain :
RewriteEngine On RewriteCond %{HTTP_HOST} ^yourdomain\.com [NC] RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R=301,L]
The additional RewriteCond line checks the hostname of the incoming request. The NC flag makes this comparison case-insensitive. Only requests matching the specified domain proceed to the redirect rule.
Note the backslash before the dot in the domain name. This escapes the dot character, which otherwise has special meaning in regular expressions. Without the backslash, the pattern could match unintended domains.
Redirecting a Specific Folder
Some situations require HTTPS only for certain sections of your website, such as login pages, shopping carts, or customer account areas. You can enforce secure connections on specific directories while leaving other areas accessible via HTTP.
Add this code to redirect a particular folder :
RewriteEngine On RewriteCond %{SERVER_PORT} 80 RewriteCond %{REQUEST_URI} ^/securefolder RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R=301,L]
Replace securefolder with the actual directory name you want to protect. The REQUEST_URI condition checks whether the requested path begins with your specified folder name.
Alternatively, place a separate .htaccess file containing the basic redirect code directly within the folder you want to secure. This approach keeps your main .htaccess file cleaner and makes the folder's security requirements more obvious.
Handling Both WWW and Non-WWW Versions
Websites can be accessed with or without the www prefix, and you should redirect both versions to a single canonical URL. This consolidated approach prevents duplicate content issues and ensures consistent branding.
To redirect everything to the www version with HTTPS :
RewriteEngine On RewriteCond %{HTTPS} off [OR] RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R=301,L]
This code triggers the redirect when either condition is true : the connection lacks HTTPS encryption, or the hostname does not begin with www. The OR flag links these conditions with logical OR rather than the default AND.
Testing Your HTTPS Redirect
After saving your .htaccess changes, immediately test the redirect to confirm it works correctly. Open a new browser window and type your domain with the HTTP prefix explicitly included.
If the redirect works, your browser should automatically jump to the HTTPS version. Check the address bar to confirm it displays https:// and shows the padlock icon indicating a secure connection.
Clearing Browser Cache
Browsers cache redirect information, which can show incorrect results during testing. If your redirect does not appear to work, clear your browser cache completely or test using an incognito or private browsing window.
Cached 301 redirects persist even after you modify the .htaccess file. A fresh browser session ensures you see the current server behaviour rather than cached instructions from previous attempts.
Testing Multiple URLs
Check several different pages on your website, not just the homepage. Try accessing interior pages, blog posts, and resource files directly via HTTP URLs to confirm the redirect applies consistently throughout your site.
If you implemented folder-specific redirects, verify that protected folders redirect correctly while unprotected areas remain accessible via HTTP as intended.
Checking for Mixed Content
After enabling HTTPS, check for mixed content warnings. These occur when your secure page attempts to load resources like images, stylesheets, or scripts via insecure HTTP connections.
Browser developer tools highlight mixed content issues. Open the console tab and look for warnings about insecure resources. Update any hardcoded HTTP links in your website code to use HTTPS or protocol-relative URLs.
Common Problems and Solutions
Several issues can prevent your .htaccess redirect from working correctly. Understanding these common problems helps you diagnose and resolve configuration errors quickly.
Redirect Loop Errors
A redirect loop occurs when your rules continuously redirect between URLs without ever reaching a final destination. Browsers display errors like "ERR_TOO_MANY_REDIRECTS" when this happens.
This typically indicates conflicting redirect rules. Check for redirects configured elsewhere, such as in your content management system settings, hosting control panel, or other .htaccess rules. Remove duplicate redirect configurations, keeping only the .htaccess version.
500 Internal Server Error
Syntax errors in .htaccess immediately trigger 500 Internal Server Error messages, making your website inaccessible. If this happens after editing your file, restore your backup immediately.
Common syntax mistakes include missing spaces between directive components, incorrect use of special characters, or typographical errors in directive names. Review your code character by character against working examples.
Redirect Not Working
When your redirect simply does not function and no errors appear, the mod_rewrite module may be disabled on your server. Contact your hosting provider to confirm mod_rewrite is enabled for your account.
Also verify you placed the code in the correct .htaccess file. Edits to an .htaccess file in the wrong directory have no effect on your website's behaviour.
SSL Certificate Errors
Redirecting to HTTPS before properly installing your SSL Certificate causes browsers to display frightening security warnings. Ensure your SSL Certificate is correctly installed and functioning before implementing the redirect.
Test HTTPS access manually by typing your URL with the https:// prefix. If this produces SSL Certificate errors, resolve the installation issues before adding redirect rules to your .htaccess file. Explore Our Technical FAQ 🔗
SEO Benefits of HTTPS Redirection
Properly configured HTTPS redirection delivers significant benefits for your search engine rankings and overall website performance.
Search Ranking Advantage
Search engines including Google explicitly factor HTTPS into their ranking algorithms. Websites using secure connections receive a ranking boost compared to equivalent HTTP sites.
This advantage grows more significant as search engines increase their emphasis on security and user experience. Implementing HTTPS now positions your website favourably for future algorithm updates.
Preserving Link Equity
The 301 permanent redirect passes ranking value from your HTTP pages to their HTTPS equivalents. External links pointing to your old HTTP URLs transfer their authority to your secure pages rather than losing that value entirely.
Without proper redirects, backlinks to HTTP pages become less valuable because they lead to non-canonical URLs. The redirect ensures your accumulated link equity benefits your current secure website.
Consolidated Analytics
Running both HTTP and HTTPS versions splits your traffic data across multiple properties. Redirecting everything to HTTPS consolidates your analytics into a single, accurate picture of your website performance.
Update your analytics configuration to track the HTTPS version as your primary property. This ensures accurate reporting and proper goal tracking going forward. Learn About Improving Your Search Engine Rankings 🔗
Securing Your Website with an SSL Certificate
Implementing HTTPS redirection requires an active SSL Certificate installed on your server. Without a valid Certificate, browsers cannot establish the encrypted connection that HTTPS provides.
Trustico® offers SSL Certificates for every requirement, from basic domain validation for personal websites to extended validation for e-commerce and enterprise applications. Our SSL Certificates work with all major web servers including Apache.
The validation process confirms your right to use the domain name and, for higher validation levels, verifies your organisation's identity. Once issued, your SSL Certificate enables the encryption that protects your visitors' data.
After installation, the .htaccess redirect ensures every visitor automatically benefits from this protection. Together, your SSL Certificate and redirect configuration create a consistently secure experience for everyone accessing your website. Discover Our Wildcard SSL Certificate Options 🔗
Frequently Asked Questions
Website administrators commonly have questions about .htaccess configuration and HTTPS redirection. The following answers address the most frequent concerns.
Does .htaccess Work on All Servers?
The .htaccess file only works on Apache web servers. If your website runs on Nginx, LiteSpeed, or Microsoft IIS, you need different configuration methods to implement HTTPS redirection.
Most shared hosting accounts use Apache, making .htaccess the appropriate solution. Check with your hosting provider if you are unsure which server software powers your account.
Can I Edit .htaccess Without Technical Knowledge?
Basic .htaccess edits like HTTPS redirection require only copying the provided code and changing the domain name. However, understanding what the code does helps you troubleshoot problems if they occur.
Always backup your existing file before making changes. If something goes wrong, restoring the backup immediately fixes the problem without requiring technical expertise.
Will the Redirect Affect My Website Speed?
Server-side redirects add minimal overhead, typically a few milliseconds to the initial request. This negligible delay is far outweighed by the performance benefits of HTTPS, including HTTP/2 support and improved caching.
Browsers that support HSTS (HTTP Strict Transport Security) can skip the redirect entirely after the first visit, connecting directly via HTTPS on subsequent requests.
Should I Use 301 or 302 Redirects?
For HTTPS migration, always use 301 permanent redirects. This tells browsers and search engines that the change is lasting, allowing them to update their records and pass full ranking value to the new URLs.
302 temporary redirects are inappropriate for HTTPS migration because they signal the change might reverse. Search engines may continue indexing HTTP versions, splitting your ranking authority.
What If My Hosting Provider Already Handles HTTPS?
Some hosting providers and content delivery networks implement HTTPS redirection at the infrastructure level. Adding .htaccess rules on top of existing redirects can cause conflicts and redirect loops.
Check your hosting control panel and CDN settings before adding .htaccess rules. If redirection is already configured elsewhere, additional .htaccess rules are unnecessary and potentially harmful. Explore Our Complete FAQ Section 🔗