How to make a redirect with .htaccess?

by aniyah.green , in category: SEO , 6 months ago

How to make a redirect with .htaccess?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

Member

by vinnie , 6 months ago

@aniyah.green 

To create a redirect using the .htaccess file, you can use the mod_rewrite module in Apache. Here is an example of how you can set up a redirect:

  1. First, make sure that the mod_rewrite module is enabled in your Apache server. You can do this by checking the server configuration files or using the following command:
1
sudo a2enmod rewrite


  1. Create or update the .htaccess file in the root directory of your website if it doesn't already exist. You can use a text editor to create or edit the file.
  2. Add the following lines to the .htaccess file to enable the RewriteEngine and set the RewriteBase:
1
2
RewriteEngine On
RewriteBase /


  1. Now, you can set up the redirect. For example, if you want to redirect all requests from example.com/old-url to example.com/new-url, you can use the following rule:
1
RewriteRule ^old-url$ /new-url [R=301,L]


The ^old-url$ part is a regular expression that matches the exact URL you want to redirect from. Then, /new-url specifies the destination URL. The [R=301,L] flags indicate that it is a permanent redirect (301) and that this is the last rule to be processed (L).

  1. Save the .htaccess file and upload it to the root directory of your website.
  2. Test the redirect by visiting the old URL (example.com/old-url). It should automatically redirect to the new URL (example.com/new-url). Make sure to clear your browser cache before testing.


Note: Always backup your .htaccess file before making any changes, as incorrect configuration could cause issues with your website.