Setting Up Redirects with Nginx on a VPS

When managing a website or application on your VPS, redirects are essential for controlling how traffic flows between URLs. Whether you’re moving to HTTPS, redirecting an old domain, or cleaning up broken links, Nginx makes it easy and efficient to handle redirections at the web server level.

In this guide, we’ll cover how to configure different types of redirects in Nginx, including:

  • Permanent redirects (301)

  • Temporary redirects (302)

  • HTTP to HTTPS

  • Non-www to www (and vice versa)

  • Path-specific rewrites

Prerequisites

  • A VPS with Nginx installed

  • Root or sudo access

  • Your site’s config file (typically in /etc/nginx/sites-available/ or /etc/nginx/conf.d/)

 1. Permanent Redirect (301)

Use this when a URL or domain has changed permanently.

✅ Example: Redirect from old domain to new domain

server {
listen 80;
server_name olddomain.com www.olddomain.com;
return 301 https://newdomain.com$request_uri;
}

🔐 Tip: Always redirect to HTTPS when possible.

2. Temporary Redirect (302)

Use this for temporary redirection (e.g., during maintenance).

server {
listen 80;
server_name olddomain.com www.olddomain.com;
return 301 https://newdomain.com$request_uri;
}

 3. Redirect HTTP to HTTPS

This is highly recommended for SEO and security.

server {
listen 80;
server_name example.com www.example.com;
return 301 https://example.com$request_uri;
}

Then configure your HTTPS server block separately:

server {
listen 443 ssl;
server_name example.com;
# SSL config here
}

 4. Redirect www to non-www (or reverse)

Choose one preferred version for consistency and SEO.

From www to non-www:

server {
listen 80;
server_name www.example.com;
return 301 $scheme://example.com$request_uri;
}

Or from non-www to www:

server {
listen 80;
server_name example.com;
return 301 $scheme://www.example.com$request_uri;
}

 5. Redirect a specific path

Example: Redirect /blog to /articles:

location = /blog {
return 301 /articles;
}

Or with full URL:

location = /blog {
return 301 https://example.com/articles;
}

Where to place these directives

All of the above directives should be placed in the appropriate server block within your site’s configuration file:

/etc/nginx/sites-available/example.com

Then symlink it to sites-enabled if needed:

ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

After Updating Configurations

Always test your Nginx configuration before reloading:

sudo nginx -t

If there are no errors:

sudo systemctl reload nginx

Bonus: Redirect All 404 Errors to Home Page

error_page 404 =301 /;

Place this inside your server block to handle broken links gracefully.

Nginx is not just a high-performance web server—it’s also a powerful tool for controlling traffic and user experience through intelligent redirects. With just a few lines of configuration, you can enforce HTTPS, guide users to the right URLs, and optimize your site for both SEO and security.