Question: How do you implement a 301 redirect in nginx?


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:

Step-by-step guide to setting up a 301 Redirect in Nginx

  1. 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.

  2. Locate the server block where you need to add the redirect: This will typically look something like this:

    server { listen 80; server_name; ... }
  3. Add the redirect: You can add a simple 301 redirect directly inside the server block. For example, to redirect from to, you would add the following line:

    rewrite ^/oldpage$ permanent;

    Alternatively, if you are moving a whole site from to, you might configure it like this:

    server { listen 80; server_name; return 301 $scheme://$request_uri; }
  4. 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
  5. Reload Nginx to apply changes: Once your configuration is error-free, reload Nginx to apply the changes:

    sudo systemctl reload nginx


  • HTTPs Configuration: If your site is running on HTTPS, ensure your redirects handle HTTP to HTTPS redirection appropriately.
  • Regular Expressions: Nginx uses regular expressions for pattern matching in redirects, so familiarizing yourself with regex in Nginx can be very useful.
  • www and non-www: Consider implementing redirects that handle both 'www' and 'non-www' versions of your URLs to maintain consistency.

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.

Other Common Website Redirects Questions (and Answers)

© ContentForest™ 2012 - 2024