Answered by
Oliver Hall
Implementing a 301 redirect in Nginx is an efficient way to permanently redirect one URL to another, which can help in maintaining SEO value when changing URL structures or migrating a website. Here’s how you can set up a 301 redirect in your Nginx configuration:
Open your Nginx configuration file: This file is commonly found at /etc/nginx/nginx.conf
or within the /etc/nginx/sites-available/
directory for specific site configurations.
Locate the server block where you need to add the redirect: This will typically look something like this:
server { listen 80; server_name example.com; ... }
Add the redirect: You can add a simple 301 redirect directly inside the server block. For example, to redirect from http://example.com/oldpage
to http://example.com/newpage
, you would add the following line:
rewrite ^/oldpage$ http://example.com/newpage permanent;
Alternatively, if you are moving a whole site from oldsite.com
to newsite.com
, you might configure it like this:
server { listen 80; server_name oldsite.com; return 301 $scheme://newsite.com$request_uri; }
Test the configuration: Before applying the changes, it's important to test your Nginx configuration for syntax errors. You can do this by running:
sudo nginx -t
Reload Nginx to apply changes: Once your configuration is error-free, reload Nginx to apply the changes:
sudo systemctl reload nginx
By correctly setting up 301 redirects, you not only keep your SEO intact but also ensure a smoother user experience by seamlessly directing visitors to the new locations of your resources.