Force both non-WWW and https in htaccess

Hi there everyone!

I have been using the following to force https:

RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://domain.com/$1 [R,L]

Which works well but now I’d like to also force non-WWW as currently https://www does not get redirected.

I can find htaccess rules for either but I’d like a portable solution that handles both so I can use it across multiple domains without altering the domain portion each time.

Can this be done?

Thanks for your time!

Can’t you just add another RewriteCond?

Put the www test above the port 80 test and use the ‘OR’ flag.

The logic should read like “If URL has www in it OR is port 80, redirect thusly”.

So then if the url comes in as http://www it will trigger. If it comes in https://www it will trigger. If it comes in http://example it will trigger.

Here are docs regarding the [OR] flag.
http://httpd.apache.org/docs/current/mod/mod_rewrite.html
Scroll about half way down to this section:

‘ornext|OR’ (or next condition)
Use this to combine rule conditions with a local OR instead of the implicit AND. Typical example:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www. [NC]
RewriteCond %{HTTP_HOST} ^(?:www.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]

Thank you all so much for your help!

This seems to be working fantastically, thank you so much for sharing it!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.