Force HTTPS non-www or www using .htaccess

You can use the following codes on you .htaccess if you want to force non-www or www on your site. The below codes works perfectly when your setup using Nginx in front of Apache as a reverse proxy.

Force non-www + HTTPS

# Force non-www+https
<IfModule mod_rewrite.c>
	RewriteEngine On
	RewriteCond %{HTTP:X-Forwarded-Proto} !https [OR]
	RewriteCond %{HTTP_HOST} ^www\. [NC]
	RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
	RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
</IfModule>
# End of Redirect

Force www + HTTPS

# Force www+https
<IfModule mod_rewrite.c>
	RewriteEngine On
	RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
	RewriteCond %{HTTP:X-Forwarded-Proto} !https
	RewriteRule (.*) https://www.%1%{REQUEST_URI} [R=301,L]
</IfModule>
# End of Redirect

These codes works perfectly with RunCloud’s Hybrid Stack (NGINX + Apache).

Share your thoughts by leaving a comment below.