Skip to main content

One post tagged with "htaccess"

View All Tags

301 Redirect: a simple guide to setting it up with .htaccess or Nginx

· 2 min read
Customer Care Engineer

how-to-set-up-301-redirect-nginx-and-htaccess

Want to redirect users and search engines to a new website address? 301 redirect is your best friend! It helps you maintain SEO rankings and avoid 404 errors. In this article, we will show you how to set up 301 redirect in .htaccess and Nginx quickly and easily.


What is a 301 redirect and why do you need it?

A 301 redirect is a permanent redirect from one URL to another. It is used to:

  • Preserve a site’s search engine rankings after changing its address.
  • Combine multiple URLs into one.
  • Avoid traffic loss and 404 errors.

How to Set Up a 301 Redirect in .htaccess (Apache)

  1. Find or сreate the .htaccess

The .htaccess file is located in the root (primary working) directory of your site. If it doesn’t exist, create a new one.

  1. Add the following code for redirection
  • For a single URL:
Redirect 301 /old-page https://yoursite.com/new-page
  • To redirect an entire website:
RewriteEngine On

RewriteCond %{HTTP_HOST} ^oldsite\.com$ [NC]

RewriteRule ^(.*)$ https://newsite.com/$1 [L,R=301]

Replace oldsite.com and newsite.com with your site’s old and new domains respectively. 

  1. Save the file

The changes will take effect immediately.


How to set up a 301 redirect in Nginx

  1. Open the nginx configuration file for your site

Connect to your server via SSH and open the necessary file in the nano text editor:

sudo nano /etc/nginx/sites-available/your-site.com.conf

Replace yoursite.com with your site’s domain. 

If you can’t find such a file, you can locate the configuration file with the following command:

sudo grep -irl name /etc/nginx
  1. Add redirect rules to the server block
  • For a single URL:
server {

listen 80;

server_name oldsite.com;

return 301 https://newsite.com/new-page;

}
  • To redirect an entire site:
server {

listen 80;

server_name oldsite.com;

return 301 https://newsite.com$request_uri;

}
  1. Save and apply the changes

Save the file using the shortcut "Ctrl + O" and exit nano with "Ctrl + X". Then apply the changes with:

sudo systemctl reload nginx

How to check if the redirect is working

After configuring, make sure your 301 redirect is active:

  • Open the old url in a browser.

Go to the old URL in your browser and make sure you are redirected to the new address.

info

It is best to perform this check in a private browser window (incognito) to avoid caching the results.