How to redirect all http requests to https and remove www?

10 April 2023   942
Comments 2
redirect htt to https.jpg

If you want to redirect easily and automatically all requests to the HTTPS version of your website without the www prefix, you can use the following code in your .htaccess file.

This code first checks if the request is not already using HTTPS and redirects it to the HTTPS version of the same URL. Then, it checks if the request is using the www prefix and removes it, redirecting the request to the same URL without the www prefix and using HTTPS.

With this code in your .htaccess file, all requests to your website with the www prefix will automatically redirect to the non-www version using HTTPS.

 

    RewriteEngine On
    # Redirect to https
    RewriteCond %{HTTPS} !=on
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    
    # Remove www prefix
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ https://%1/$1 [L,R=301]

Comments

  1. Thank you for sharing such useful topic.
    It was very helpful to me and I tried this works prefect !

  2. Works fine and thank you.

Enter your comment below. Fields marked * are required. You must preview your comment before submitting it.