Force www in your .htaccess file in cPanel (For WordPress & All Sites)
Enforce WWW or Non-WWW in Your .htaccess File Using cPanel
Many website owners have a preference for how their domain appears in the browser address bar: with “www” (e.g., www.example.com) or without (e.g., example.com). While this choice doesn’t affect site accessibility, it can be a branding or personal preference. This guide provides step-by-step instructions on how to enforce either version using your .htaccess file within cPanel.
Accessing Your .htaccess File
- Log in to cPanel: Access your web hosting control panel.
- Open File Manager: Locate the “Files” category and click on “File Manager.”
- Configure Settings: Click the “Settings” tab in the top right corner.
- Show Hidden Files: Select the document root for your domain and ensure the “Show Hidden Files” checkbox is checked. Click “Save.”
- Locate .htaccess: Find the .htaccess file in the file list and right-click on it.
- Edit .htaccess: Choose the “Edit” option from the right-click menu. This will open the file in a text editor.
Enforcing WWW in Your .htaccess File
To redirect visitors from the non-WWW version of your domain to the WWW version, paste the following code into your .htaccess file:
#Force www:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]
Important Note: Replace example.com
with your actual domain name (without WWW). For example, use mydomain.com
or yourwebsite.net
.
Enforcing Non-WWW in Your .htaccess File
To redirect visitors from the WWW version to the non-WWW version, use this code:
#Force non-www:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301,NC]
Again, remember to replace example.com
with your actual domain name.
Understanding the Code
RewriteEngine on
: This line activates the rewrite engine within Apache, allowing the .htaccess file to modify how incoming requests are handled.RewriteCond %{HTTP_HOST} ^example.com [NC]
: This condition checks if the requested host name matches your domain name without “www,” ignoring case sensitivity ([NC]
).RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]
: This rule redirects any requests matching the condition to the WWW version of your domain. The[L,R=301,NC]
flags indicate that this is the last rule to be processed (L
), it’s a permanent redirect (R=301
), and case sensitivity is ignored (NC
).
Saving Changes
After pasting and modifying the code, save the .htaccess file. The changes should take effect immediately, and visitors will be redirected to your preferred domain version.
By following these steps, you can easily control how your domain appears in the address bar, ensuring consistency and reinforcing your brand identity.