DEV Community

Cover image for How to Force www or non-www in htaccess File
Muhammad Idrees
Muhammad Idrees

Posted on • Edited on

1

How to Force www or non-www in htaccess File

  • Step1: Log into your cPanel.
  • Step2: Find the Files category and click on the File Manager icon.
  • Step3: Click Settings at the top right corner.
  • Step4: Choose the document root for the domain you are working with and be sure the checkbox next to Show Hidden Files is checked. Click the Save button.
  • Step5: Look for the .htaccess file and right-click on it. This brings up a menu. Find and click on the Edit option
  • Step6: You are now in the text editor. Place either selection of code in the file and click on the Save Changes button at the top right corner of the screen. Be sure to replace 'example.com' with your actual domain name. NOTE: do not place both selections of code in the file as it will cause an error.
#Force www:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]

#Force non-www:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]
Enter fullscreen mode Exit fullscreen mode
  • Step7: Now, when you type in your domain name with either www in front or not, it should display as you have set it in the .htaccess file.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (2)

Collapse
 
aslasn profile image
Ande

lmao i thought you asked for help. so I came to help. and ...

Collapse
 
midexigner profile image
Muhammad Idrees

what you need for help

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay