How to redirect a website to https://non-www using .htaccess

  1. Enable mod_rewrite: Add the following line to the top of your .htaccess file:
RewriteEngine On
  1. Exclude www for both HTTP and HTTPS requests: Add the following code block to redirect all requests (HTTP and HTTPS) to the non-www version of the URL:
RewriteCond %{HTTP_HOST} =www\.(.*) [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

Explanation of the code:

  • RewriteEngine On: Enables the mod_rewrite module, which is required for URL rewriting.
  • RewriteCond %{HTTP_HOST} =www\.(.*): Checks if the current request includes a www prefix.
  • [NC]: Indicates that the www\. pattern should be matched case-insensitively.
  • RewriteRule ^(.*)$ https://%1/$1 [R=301,L]: Redirects all requests, including HTTP and HTTPS, with a www prefix to the corresponding non-www URL using a permanent 301 redirect. The R=301 flag tells Apache to use a permanent redirect, and the L flag tells Apache to stop processing the rewrite rules after this rule is matched.

Leave a Reply

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