htaccess redirects

#2024-09-16

Had some problems redirecting domains on my new server recently. Took a while to get the redirects working correctly so sharing my note-to-self here, might help someone.

# Redirect http, https and www to a different domain
RewriteCond %{HTTP_HOST} ^old-domain\.example$ [OR]
RewriteCond %{HTTP_HOST} ^www\.old-domain\.example$
RewriteRule ^(.*)$ "https\:\/\/new-domain\.example\/$1" [R=301,L]

# Redirect www to non-www and https
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

# Redirect http to https
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]