NGINX redirects are commonly used to forward users and search engines from one URL to another. Redirects are helpful when changing domain names, restructuring URLs, enforcing HTTPS, or handling removed pages. In this knowledge base article, we explain how to create redirects in NGINX using different methods.
Prerequisites
Before creating redirects in NGINX, confirm that:
- You have access to the server with NGINX installed.
- You can edit the NGINX configuration files.
- You have root or sudo privileges.
Types of Redirects in NGINX
The most commonly used redirects are:
- 301 Redirect (Permanent): Indicates that the URL has been permanently moved.
- 302 Redirect (Temporary): Indicates a temporary redirection.
Create a Redirect Using the return Directive (Recommended)
The return directive is the simplest and most efficient way to create redirects in NGINX.
Example: 301 Redirect
server {
listen 80;
server_name example.com;
return 301 https://www.example.com$request_uri;
}
This configuration permanently redirects all traffic from example.com to www.example.com.
Example: 302 Redirect
return 302 https://example.com/new-page;
Create a Redirect Using the rewrite Directive
The rewrite directive provides more flexibility and is useful for complex URL patterns.
Example: Redirect a Specific Page
rewrite ^/old-page$ /new-page permanent;
Example: Redirect Using Regular Expressions
rewrite ^/blog/(.*)$ /articles/$1 permanent;
Redirect HTTP to HTTPS
To force HTTPS for your website, add the following configuration:
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}
Redirect One Domain to Another
server {
listen 80;
server_name olddomain.com;
return 301 https://newdomain.com$request_uri;
}
Test and Reload NGINX Configuration
After adding or modifying redirect rules, test the NGINX configuration:
nginx -t
If the test passes, reload NGINX to apply the changes:
systemctl reload nginx
Important Notes
- Always test redirects in a staging environment if possible.
- Incorrect rewrite rules can cause redirect loops.
- Use 301 redirects for SEO-friendly permanent changes.
- Back up configuration files before making changes.
Conclusion
This concludes the guide on creating redirects in NGINX. By using the return or rewrite directives, you can efficiently manage URL redirections to improve site structure, security, and user experience.