Check this Out!Visit our social network pages for recent updates!

Apache2 301 Redirect Without htaccess File on Ubuntu 17.04

Few days ago we showed students and new users how to easily do 301 redirects using Apache2 and Nginx web servers on Ubuntu 17.04 systems. In that post, the method we used to perform Apache2 redirect was to use the .htaccess file in the root directory or DocumentRoot of the site.

This is the most used method to do a redirect using Apache2.

This post is going to show you how to do the same Apache2 redirect without using the .htaccess file in the root directory.

To read our previous post on this topic, please check the link below.

Redirect HTTP to HTTPS using Nginx or Apache2 on Ubuntu 17.04

Just like Nginx, one can use Apache2 virtual host to do a redirect. This method is easier to do than using the .htaccess file.

When you’re ready, open the website configuration file you want to redirect. This is usually located at /etc/apache2/sites-available/sitename

The highlighted portion of the sample file below shows the redirect statement.

Redirect Without WWW Subdomain


<VirtualHost *:80>	
        ServerName www.ubuntu1704.com
        ServerAlias www.ubuntu1704.com

        Redirect / http://ubuntu1704.com
</VirtualHost>

<VirtualHost *:80>        
        ServerName ubuntu1704.com
        ServerAlias ubuntu1704.com

        DocumentRoot /var/www/html

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

### Other configs below
.........
</VirtualHost> 
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

The configuration above redirect all requests to the domain without the WWW sub domain.

Redirct With WWW Subdomain

To redirect all requests to the domain with the WWW subdomain, change the configuration as shown below.

<VirtualHost *:80>	
        ServerName ubuntu1704.com
        ServerAlias ubuntu1704.com

        Redirect / http://www.ubuntu1704.com
</VirtualHost>

<VirtualHost *:80>        
        ServerName www.ubuntu1704.com
        ServerAlias www.ubuntu1704.com

        DocumentRoot /var/www/html

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

### Other configs below
.........
</VirtualHost> 
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

 

Restart Apache2 webserver and the site will properly redirect.

Summary:

This is a follow up post from our last tutorial on this topic. If you want to do a proper 301 redirect using Apache2, then configure your site as shown above. The most used method to performing 301 redirects using Apache2 is using the .htaccess file.

This method is the easiest and you should probably use it instead of the .htaccess file.