How to create Nginx redirects
- List the old paths and new URLs, one pair per line.
- Choose the redirect code: 301 permanent or 302 temporary (or 308 and 307 to keep the request method).
- Add the generated
locationblocks inside theserver { }block for your site, typically in/etc/nginx/sites-available/. - Run
sudo nginx -tto check the configuration, thensudo systemctl reload nginx.
Fast, explicit rules
For single pages the generator uses exact-match locations, location = /old-page { return 301 /new-page; }, which Nginx checks first and which are the fastest kind of match. Folder redirects use a prefix location with a rewrite that keeps the rest of the path. Old URLs with query strings get a check on $args inside the location, because Nginx locations never match the query string.
For HTTPS and www normalisation, the recommended Nginx approach is a separate small server block that listens on port 80 (or on the unwanted host name) and returns a single redirect to the canonical address, rather than if statements in your main block. The output includes that block as a comment for you to adapt.
For hundreds or thousands of redirects, consider an Nginx map with an include file, which keeps the main configuration tidy. The rules are generated in your browser.
FAQ
Where do Nginx redirects go?
Inside the server block for the site, in the configuration file under sites-available or conf.d. Reload Nginx after editing.
What is the difference between return and rewrite?
return sends a response immediately and is simplest for fixed redirects. rewrite uses a regular expression and is needed when part of the old path is reused.
Do I need to restart Nginx?
A reload is enough and does not drop connections: systemctl reload nginx or nginx -s reload.