301 rewrite: force https plus non-www direction

Hi, I am a non-www advocator, but am not a professional tech/coder. I was wondering if anyone can tell me how to make the above two rewrites, the most direct and official way.

My search has given me the following:

RewriteCond %{HTTPS} !on
RewriteRule ^/(.*)$ https://%{SERVER_NAME}/$1 [R=301,L]

And this is force-https rewrite. I can go into the panel – configurations – rewrite rules, and put the codes inside and save them.

But for the www to non-www part, well, I tried a couple of times but seemed it’s not working.

My codes are like this:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

RewriteCond %{HTTPS} !on
RewriteRule ^/(.*)$ https://%{SERVER_NAME}/$1 [R=301,L]

Is this config right?

For www to non-www


RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\\.(.*)$ [NC]
RewriteRule ^/(.*)$ http://%1/$1 [R=301,L]

@usmannasir said:
For www to non-www


> RewriteEngine On
> RewriteCond %{HTTP_HOST} ^www\\.(.*)$ [NC]
> RewriteRule ^/(.*)$ http://%1/$1 [R=301,L]
> 

make it

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\\.(.*)$ [NC]
RewriteRule ^/(.*)$ https://%1/$1 [R=301,L]

redirect to HTTPS

Thank you, usmannasir and qtwrk. I made some small adjustments.

RewriteCond %{HTTP_HOST} ^www\\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301]

RewriteCond %{SERVER_PORT} ^80$
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

But the bottom block seems not fully working. My condition is that besides mydomain.tld, I set another domain, forums.mydomain.tld, just like forums.cyberpanel.net.

I applied successfully a wildcard cert from Letsencrypt via acme.sh scripts, *.mydomain.tld, so I don’t have to set a forums.mydomain.tld separately for the forum domain.

Now the problem is, mydomain.tld can switch from 80 to 443 via rewriterules in that .htaccess file, forums.mydomain.tld will not. It can be accessed both by http and https.

The forums.mydomain.tld is put in a folder called forums under mydomain’s root, like this
/home/mydomain.tld/public_html/forums. I didn’t set it in PowerDNS, but set it via Cloudflare’s A record, point it to my server’s IP addr.

So judging from your expertise, where should I go to make the forums part, forums.mydomain.tld forced to https/443? Or should I directly touch the httpd.conf?