Apache redirect www to non-www and HTTP to HTTPS

Nirjonadda

Well-Known Member
May 8, 2013
736
27
78
cPanel Access Level
Root Administrator
Please let me know that how to Apache redirect www to non-www and HTTP to HTTPS?

Code:
http://example.com
http://www.example.com
https://example.com
https://www.example.com
https://www.example.com/all-directory/sub-directory/
To

Code:
https://example.com
 

rangka_kacang

Active Member
Jan 31, 2018
35
3
8
Malaysia
cPanel Access Level
Root Administrator
Hello.

Write the following to your .htaccess file. This will redirect all traffics from www. (and it's sub directories) with and/or without https to

https:// yourdomain.com

Code:
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]
p/s I have not tested this yet as I'm currently on the move. The 301 redirect is to avoid crawl bots from getting drunk.

Thank you.
 

Nirjonadda

Well-Known Member
May 8, 2013
736
27
78
cPanel Access Level
Root Administrator
Hello.

Write the following to your .htaccess file. This will redirect all traffics from www. (and it's sub directories) with and/or without https to

https:// yourdomain.com

Code:
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]
p/s I have not tested this yet as I'm currently on the move. The 301 redirect is to avoid crawl bots from getting drunk.

Thank you.

Yes are working but only not working one sub directories URL. Please let me know this issue.

Code:
https://www.mysite.com/xenforo/admin to https://mysite.com/xenforo/admin
 

cPanelMichael

Administrator
Staff member
Apr 11, 2011
47,909
2,227
463
Hello,

Assistance with customizing Mod_Rewrite rules isn't offered, but note you may find more user-feedback to this type of question on a website such as StackOverflow. Or, you may want to consult with a qualified system administrator if you need help customizing Mod_Rewrite rules and the user-feedback you receive is not sufficient. We provide a list of companies offering system administration services at:

System Administration Services | cPanel Forums

Thank you.