Redirect www to non-www https.

I am trying to redirect all traffic from http/https www to https only non-www. I have got http to https setup using the following on apache 2.4:

        RewriteCond %{HTTPS} off
        RewriteCond %{HTTP:X-Forwarded-Proto} !https
        RewriteRule ^(.*)$ https://*%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
        RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

It also needs to work inside of the virtual hosts conf file and not .htaccess as my cms could overwrite the .htaccess on upgrades. I want to add www redirect as my site may have users that are used to typing www. Thanks for all of your help in advance.

Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.

hello i have a problem, i want to redirect to non www but its not working when i use https://www it just works with http://www. or with http://domain those last to redirect correctly to https://domain but not when i add www and https, why is that?

Hey there,

Here is a great tutorial that outlines redirecting www subdomains to non-www URL’s.

Here’s an example of the rewrite rule that should work and still forward to https:

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

Happy coding,

Jon Schwenn Platform Support Specialist DigitalOcean