How to Force HTTPS and Remove ‘www’ Using .htaccess

How to Force HTTPS and Remove ‘www’ Using .htaccess

If you’re running a website on an Apache server, it’s essential to enforce security and consistency in your URLs. By using the .htaccess file, you can automatically redirect HTTP traffic to HTTPS and remove ‘www’ from your URLs. This helps improve SEO, enhances security, and ensures a uniform user experience.

Why Use .htaccess for URL Redirects?

  1. Security – Redirecting HTTP to HTTPS ensures data encryption.
  2. SEO Benefits – Prevents duplicate content issues by maintaining a single version of URLs.
  3. User Experience – Ensures consistent access to your website without confusion.

Steps to Implement the Code

Step 1: Locate the .htaccess File

The .htaccess file is usually located in the root directory of your website. If you can’t find it:

  • Make sure hidden files are visible in your FTP client.
  • If it doesn’t exist, create a new .htaccess file using a text editor.

Step 2: Add the Code to Your .htaccess File

Copy and paste the following code into your .htaccess file:

# HTTPS Rewrite
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# BEGIN WordPress

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

# END WordPress

# Remove www from URL
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

Step 3: Save and Upload the File

After adding the code, save the .htaccess file and upload it to your website’s root directory via FTP or your hosting control panel.

Step 4: Test the Redirects

  • Open a browser and type http://yourwebsite.com. It should automatically redirect to https://yourwebsite.com.
  • Try http://www.yourwebsite.com, and it should redirect to https://yourwebsite.com without www.

Understanding the Code

Forcing HTTPS

The RewriteCond %{HTTPS} off checks if the connection is not secure.

The RewriteRule then redirects all traffic to the HTTPS version.

WordPress Permalink Rules

This ensures that WordPress can handle pretty permalinks properly.

Removing ‘www’ from URLs

The RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] checks if the URL contains www.

The RewriteRule redirects it to the non-www version.

Conclusion

Implementing these .htaccess rules helps secure your website and maintain a clean URL structure. If you face any issues, ensure that the .htaccess file has the correct permissions (644 recommended) and that mod_rewrite is enabled on your server.

Need more help? Let me know in the comments!

Related articles

You may also be interested in

Headline

Never Miss A Story

Get our Weekly recap with the latest news, articles and resources.
Cookie policy
We use our own and third party cookies to allow us to understand how the site is used and to support our marketing campaigns.