Redirect all pages to non-www and HTTPS in WordPress

To redirect all URLs from www to non-www and also to redirect from http to https, this code snippet to be added to .htaccess file at the top should do the trick.

So https://example.com

# BEGIN Redirects
RewriteEngine On
# 301 redirect www to non-www
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
# 301 redirect to https
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# END Redirects

If you still want the www way instead https://www.example.com

# BEGIN Redirects
RewriteEngine On
# 301 redirect to www
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# 301 redirect to https
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# END Redirects

6 Comments

  1. Imagbox on March 14, 2023 at 2:57 pm

    Hi, I tried to add www to non-www to WP snippets, but failed to save the snippet:

    Don’t Panic

    The code snippet you are trying to save produced a fatal error on line 2:
    syntax error, unexpected ‘On’ (T_STRING)

    The previous version of the snippet is unchanged, and the rest of this site should be functioning normally as before.

    Please use the back button in your browser to return to the previous page and try to fix the code error. If you prefer, you can close this page and discard the changes you just made. No changes will be made to this site.
    __
    Also I tried to add it directly to .htaccess file – it was saved normally, but nothing changed.

    www to non-www – works only on chrome and opera, but failed on firefox and safari(

  2. akaslot on March 14, 2022 at 7:00 pm

    Hi It not working for me

  3. Segun Wonda on July 23, 2021 at 11:10 am

    I have use all methods for the redirection including adding code to the .htaccess.
    None of those methods works for me.

  4. Keith Mvula on May 4, 2021 at 7:54 pm

    this is not working, Am using litespeed server

  5. Alan on February 15, 2021 at 11:15 am

    Hi. Great. How do add trailing slashes to urls if some do not have it?

  6. Elise on January 15, 2021 at 11:38 pm

    Thank you!

Leave all Comment