配置apache重定向non-www ->www

By default, Apache doesn’t allow the use of .htaccess file, so the steps will be a little different:

  1. Enable mod_rewrite by running the following command:
    $ sudo a2enmod rewrite
    Then, restart the Apache web server:
    $ sudo systemctl restart apache2
  2. Enable .htaccess with the command:
    $ sudo vi /etc/apache2/sites-available/000-default.conf
    Add the following code before the <VirtualHost> line:
    <Directory /var/www/html>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Require all granted
    </Directory>
    Then, restart Apache.
  3. To create the .htaccess file, enter the command:
    $ sudo vi /var/www/html/.htaccess
  4. Add the following lines to the file:
    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^yourdomain.com [NC]
    RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [L,R=301]
  5. Restart the Apache server.

All site visitors using the non-www URL should now be redirected to the www version.

Source: https://www.hostinger.com/tutorials/cpanel/how-to-redirect-non-www-urls-to-www#Apache

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *