Nginx Redirect (Rewrite) Old Domain To New Domain With HTTP 301

To redirect an old domain to a new domain using an HTTP 301 redirect in Nginx, you can add the following code to your Nginx configuration file:

server {
listen 80;
server_name olddomain.com;
return 301 $scheme://newdomain.com$request_uri;
}

This code will redirect all traffic from olddomain.com to newdomain.com with a permanent HTTP 301 redirect. The $scheme variable captures the scheme (HTTP or HTTPS) used for the original request, and the $request_uri variable captures the original request URI, which will be appended to the new domain.

After making the change, don’t forget to reload Nginx for the changes to take effect:

sudo nginx -s reload

Leave a Comment