Nginx Redirect Generator

Generate Nginx redirect configuration for URL redirects and HTTPS enforcement.

Relative path to match
Destination URL or path

Frequently Asked Questions

How do redirects work in Nginx?

Nginx handles redirects in the server block configuration using the return or rewrite directives. The return directive is preferred for simple redirects — it is faster and easier to read: return 301 https://example.com$request_uri. The rewrite directive uses regular expressions for more complex URL transformations. Unlike Apache's .htaccess, Nginx configuration requires server-level access (typically /etc/nginx/sites-available/) and a configuration reload after changes.

What is the difference between return and rewrite in Nginx?

return immediately sends the specified HTTP status code and URL to the client — it is fast, clear, and sufficient for most redirect scenarios. rewrite uses PCRE regular expressions to transform the request URI before Nginx processes it further — it is more powerful but also more complex and slightly slower. For simple permanent or temporary redirects, always prefer return. Use rewrite only when you need to capture parts of the URL with regex groups (e.g. restructuring URL patterns).

How do I redirect HTTP to HTTPS in Nginx?

Create a separate server block listening on port 80 that redirects to HTTPS: server { listen 80; server_name example.com www.example.com; return 301 https://$host$request_uri; }. This is more efficient than using rewrite or if statements. Place your HTTPS configuration in a separate server block listening on port 443 with ssl. After updating the configuration file, test with nginx -t and reload with nginx -s reload or systemctl reload nginx.

How do I redirect www to non-www (or vice versa) in Nginx?

To redirect www to non-www: add a server block for www.example.com that returns 301 https://example.com$request_uri. To redirect non-www to www: reverse the domains. Both server blocks should be in your Nginx configuration file. Use exact server_name matching (server_name www.example.com;) rather than wildcard patterns for clarity. Ensure both domains have valid SSL certificates if using HTTPS redirects.