Member-only story
Redirecting Domains with Nginx: A Comprehensive Guide
2 min readMay 16, 2024
Redirecting domains is a common requirement in web server configuration, whether you’re migrating to a new domain, consolidating multiple domains, or simply optimizing your website’s SEO. Nginx, a popular web server known for its speed and flexibility, offers several methods to accomplish domain redirections efficiently. In this guide, we’ll explore various scenarios and methods for redirecting domains using Nginx.
- Setting Up a Basic HTTP to HTTPS Redirect:
- Redirecting HTTP traffic to HTTPS is essential for security and SEO purposes.
- Use the
return
directive to issue a permanent redirect (HTTP 301) from HTTP to HTTPS. - Example configuration:
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
- Redirecting from www to non-www (or Vice Versa):
- Consistency in domain usage (with or without www) is crucial for SEO and brand identity.
- Use a server block to redirect requests from one version of the domain to the other.
- Example configuration (redirect from www to non-www):
server {
listen 80;
server_name www.example.com;
return 301 https://example.com$request_uri;
}