A 301 indicates a permanent redirect from one URL to another, ensuring that any users who access the old URL will be automatically directed to the new one. In most cases it is the best method for implementing redirects. In this article we will provide a step-by-step guide to creating a permanent 301 redirect in Apache.
When to Use 301 Permanent Redirect
Whilst there are different types of Redirects (301, 302, meta refresh, etc) the permanent redirect (301) is preferred to be used in the following cases:
- When permanently moving a page URL to another one (e.g. www.mycompany.com/about becomes www.mycompany.com/about-us)
- When deleting a page, a permanent redirect must be used so that a visitor does not bounce. You can use the redirect to take the user to another, relevant page.
- Moving a Website to another Domain (e.g. www.mycompany.com becomes www.XYZcompany.com)
- Changing URL Alias structure (e.g. you want to change www.domain.com/categories/2023/September/ into www.domain.com/archive/2023/09)
- Switching your website from www to non-www and/or from http to https
- When resolving the “trailing slash” issue – remember that pages with and without trailing slash “/” are considered as different pages. This may probably create issues with your website’s sitemap and eventually with search engine ranking, so resolving it must be made carefully and with the use of permanent redirect.
Prerequisites
In order to follow this guide, you will need shell access as an admin user to a server that has Apache installed.
Three Easy Steps to Create Permanent 301 Redirect in Apache
Step 1
Depending on your installation setup and Operating system (Debian, Ubuntu, AlmaLinux, CentOS, etc), the Apache configuration file may be present in one of the following locations:
1. /etc/apache2/httpd.conf
2. /etc/apache2/apache2.conf
3. /etc/httpd/httpd.conf
4. /etc/httpd/conf/httpd.conf
For example if the file is located at /etc/apache2/httpd.conf then you will execute the following command to open the Apache Server configuration file for editing.
root@localhost:~ vi /etc/apache2/httpd.conf
Step 2
Now we will modify the configuration file to enable redirection. Assuming you want to redirect your website www.domain1.com to domain www.domain2.com then edit your configuration file as follows (see text in bold).
<VirtualHost *:80>
ServerName www.domain1.com
Redirect 301 / http://www.domain2.com/
</VirtualHost>
<VirtualHost *:80>
ServerName www.domain2.com
</VirtualHost>
Step 3
Save the file and exit.
To apply changes, restart Apache server by running the following command.
root@localhost:~ systemctl restart apache2
This is it! You have successfully created a permanent 301 Redirect in Apache!