frame

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Sign In Register

[Apache/Nginx] How to redirect non-www to www URLs?

Apache

If on your VPS is running Apache web server, you’ll also need to edit the .htaccess file. So to do that, make sure that you can connect to your VPS via root with sudo privileges.
By the way, by default, Apache doesn’t allow the use of .htaccess file, so you will need to enable that.

  1. Connect to your VPS as root with sudo privileges.
  2. Enable mod_rewrite by running the following command:

sudo a2enmod rewrite

  1. After that, you need to restart Apache web server on your VPS:

sudo systemctl restart apache2

  1. Enable .htaccess with the command:

sudo vi /etc/apache2/sites-available/000-default.conf

  1. Then add the following code before the line:
  <Directory /var/www/html>
  Options Indexes FollowSymLinks MultiViews
  AllowOverride All
  Require all granted
  1. After that, restart Apache.

  2. To create the .htaccess file, use this command:

sudo vi /var/www/html/.htaccess

  1. Then add the following lines to the file:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^yourdomain.com [NC]
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [L,R=301]

Replace yourdomain.com with your actual domain name and save it.

  1. Then restart the Apache server on your VPS:

sudo systemctl restart apache2

Nginx

If you have VPS with NGINX, follow the tutorial below to redirect non-www URLs to www:

  1. Log in to your VPS using via SSH.
  2. Navigate to the directory /etc/nginx/.
  3. Then use this command to view the directory content:

sudo ls - la

  1. Next enter your NGINX password.
  2. Type in the following command to edit the nginx.conf file:

sudo nano nginx.conf

  1. Add the following lines of code, replacing yourdomainname.com with your actual domain name:

server {
server_name yourdomainname.com;
return 301 $scheme://www.yourdomainname.com$request_uri;
}

  1. Then you need to enter the following command to restart nginx web server on your VPS:

sudo systemctl restart Nginx

In addition to redirecting non-www to www URLs, you can also run other redirects through NGINX, such as HTTP to HTTPS and other page redirects.

Tagged:
Sign In or Register to comment.

Time4VPS

Learn how to install a web and database server, email, FTP client or other applications. Discover and share information on server security or optimization recommendations.
Feel free to join our constantly expanding community, participate in discussions, strengthen your knowledge on Linux and Windows server management!
© 2013 - 2024 Time4VPS. All rights reserved.

Get In Touch