How to remove www from url in htaccess

As you probably noticed a long time ago, online websites can be accessed either with or without their www. prefix. For example www.linuxconfig.org and linuxconfig.org.

If you own a website, it’s best practice to either enforce the www. prefix across your website, or drop it completely. This creates consistency across all of your URLs, which looks pleasing any can also be beneficial for SEO and other purposes.

In this tutorial, you’ll learn how to remove the www. prefix from your URLs through .htaccess files in Apache. It works by automatically redirecting URLS like www.linuxconfig.org to linuxconfig.org. This is a simple fix that you can even apply if you’re using a managed hosting service and only have FTP access to your web server.

In this tutorial you will learn:

  • How to remove www from url in htaccess
Configuring htaccess file to remove www prefix
Configuring htaccess file to remove www prefix
Software Requirements and Linux Command Line Conventions
Category Requirements, Conventions or Software Version Used
System Any Linux distro
Software Apache Web Server
Other Privileged access to your Linux system as root or via the sudo command.
Conventions # – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
$ – requires given linux commands to be executed as a regular non-privileged user

Remove www from URL




The htaccess file can be placed in your website’s root directory. It has a dot at the beginning of the file, indicating that it’s a hidden file. The name will be like this: .htaccess

Inside the .htaccess file, paste the following text.

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ %{REQUEST_SCHEME}://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Add www to URL

In case you’d like your URLs to redirect to the www. prefix instead, you can paste this code inside the .htaccess file.

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

Conclusion

When you are done make sure that you test both URL versions. Both URLs will still access your site, but only one will be rewritten.



Comments and Discussions
Linux Forum