301 Redirect Old Domain to New Domain in Nginx

If you ever need to switch from an old domain name to a new domain name in nginx, you can use the following block:

server {
# 301 redirect for old to new domain
server_name olddomain.com;
rewrite ^/(.*)$ http://newdomain.com/$1 permanent;

Before saving your changes, run a quick syntax check:

nginx -t

..then restart nginx to see your changes:

nginx reload