HomeDeveloper's StuffHow to Create Redirects with Nginx

How to Create Redirects with Nginx

A redirect is a way to send both users and search engines to a different URL from the one they initially requested. This guide will walk you through the basics of redirects and how to implement them using Nginx, making your website management journey smoother and more efficient. The simplicity of Nginx configuration files makes it an accessible tool for setting up redirects.

How to Create Redirects in Nginx

Creating redirects in Nginx is done by modifying the server configuration files. The primary configuration file for Nginx is located at /etc/nginx/nginx.conf. Individual site configurations reside in /etc/nginx/sites-available and are enabled by linking to /etc/nginx/sites-enabled. Familiarizing yourself with these files is key to successfully managing redirects.

Implementing a 301 Permanent Redirect

A 301 redirect is used when a page has been moved permanently. To implement a 301 redirect in Nginx, you would add the following line to your server configuration block:

rewrite ^/old-page$ http://www.yourdomain.com/new-page permanent;
Implementing a 302 Temporary Redirect

A 302 redirect is similar but is used when the move is temporary. The Nginx configuration line would look like this:

rewrite ^/old-page$ http://www.yourdomain.com/new-page redirect;
Creating Wildcard Redirects

For multiple URL changes, wildcard redirects are handy. With Nginx, you can use regular expressions to match patterns:

rewrite ^/old-folder/(.*)$ http://www.yourdomain.com/new-folder/$1 permanent;
Redirecting WWW to Non-WWW

Canonicalizing your domain is crucial for SEO. Here’s how you redirect the www version of your site to the non-www:

server {
    server_name www.yourdomain.com;
    return 301 $scheme://yourdomain.com$request_uri;

Testing and Troubleshooting Your Redirects

After setting up redirects, testing them is essential to ensure they work as intended.

How to Test Redirects

You can test redirects by visiting the old URLs and observing whether you’re taken to the new location. Tools like curl are also handy for testing redirects non-interactively.

Solving Common Redirect Issues

If a redirect isn’t working, check for typos in the URL patterns or incorrect file paths. Ensure that you reload Nginx after making changes (sudo systemctl reload nginx) so that your updates take effect.

Avoid creating long chains of redirects, as they can slow down page load times and impact SEO. Consolidate multiple-step redirects into a single step where possible. And for complex redirect rules, Nginx allows the use of regular expressions. This is advanced usage and requires careful testing.

Conclusion and Further Learning

You’re now equipped with the knowledge to implement redirects using Nginx. While there is much more to learn, this guide provides a solid foundation for managing web traffic effectively.

Scroll to Top