Redirecting your website from www to non-www and from http to https is crucial for modern web practices. This not only improves security but also ensures a consistent user experience and better search engine rankings. In this article, we will guide you through the process of implementing these redirects effectively, with practical examples.
For websites hosted on Apache servers, the .htaccess file is a powerful tool to manage redirects. Follow these steps:
Access Your .htaccess File: This file is located in the root directory of your website. If it doesn't exist, create it using a text editor.
Add Redirect Rules: Insert the following code to redirect all traffic to the non-www and https version of your site:
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [L,R=301]
Imagine your website is http://www.example.com. After adding the above rules to your .htaccess file, visiting http://www.example.com will automatically redirect to https://example.com.
For Nginx servers, you'll need to modify your server block configuration:
Access the Configuration File: Typically, this file is located at /etc/nginx/nginx.conf or in the /etc/nginx/sites-available/ directory.
Add Redirect Rules: Insert the following code in the server block configuration:
server {
listen 80;
server_name www.example.com example.com;
return 301 https://example.com$request_uri;
}server {
listen 443 ssl;
server_name www.example.com;
return 301 https://example.com$request_uri;ssl_certificate /path/to/ssl_certificate.pem;
ssl_certificate_key /path/to/ssl_certificate_key.pem;
}
For the domain http://www.example.com, after adding the above configuration, any request to http://www.example.com or http://example.com will redirect to https://example.com.
If you use Cloudflare, setting up redirects is straightforward:
www and http traffic to non-www and https.
http://www.example.com/*https://example.com/$1301 (Permanent Redirect)For a domain like http://www.example.com, configuring the above page rule in Cloudflare will ensure all traffic is redirected to https://example.com.
After setting up your redirects, it's essential to verify that they work correctly. Use tools like:
http://www.example.com and checking if it redirects to https://example.com.Implementing redirects from www to non-www and http to https is essential for modern web management. It enhances security, improves SEO, and ensures a consistent user experience. By following the steps outlined in this guide and using the provided examples, you can set up these redirects efficiently and avoid common pitfalls.