Nginx Redirect URL With HTTP/1.1 301 Moved Permanently Header

In Nginx, you can use the return directive to redirect a URL with the HTTP/1.1 301 Moved Permanently header. Here’s how:

  1. Open the Nginx configuration file:
$ sudo nano /etc/nginx/nginx.conf
  1. Add the following code to the server block for the domain you want to redirect:
server {
listen 80;
server_name <old_domain>;
return 301 $scheme://<new_domain>$request_uri;
}

Replace <old_domain> with the old domain name and <new_domain> with the new domain name.

  1. Save the changes to the configuration file.
  2. Test the configuration:
$ sudo nginx -t

If the test is successful, you will see the following output:

nginx configuration file /etc/nginx/nginx.conf test is successful
  1. Reload Nginx:
$ sudo nginx -s reload

This will reload Nginx with the new configuration, and any requests to the old domain will now be redirected to the new domain with the HTTP/1.1 301 Moved Permanently header.

Note that you may need to adjust the above steps to match your specific Nginx configuration, and you may also need to make changes to your DNS settings to point the old domain to the new domain.

Leave a Comment