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

September 8, 2019

I‘ve changed the domain name from to which is shorter and easy to remember. How do I redirect old domain to new domain with “HTTP/1.1 301 Moved Permanently” status code under nginx web server running on Unix like operating systems?

Nginx web server comes with module called HttpRewriteModule. Use this module to change URI using regular expressions (PCRE), and to redirect and select configuration depending on variables. All you have to do is capture old domain and redirect to new domain. Edit /usr/local/nginx/conf/nginx.conf or /etc/nginx/nginx.conf, run:
# vi /usr/local/nginx/conf/nginx.conf
Append the following line in server{ ... } block after declaring server_name:

rewrite ^ $scheme:// permanent;

In this case all requests to the uri such as,,, all are redirected to with code 301. However, you may want to copy and pass the URL too, try:

 rewrite ^ $scheme://$request_uri permanent;

The $request_uri variable is equal to the original request URI as received from the client including the args. In other word redirect url as follows with 301 status code: to to to to

Sample code block:

### redirect$URI to$URI with 301 ###
  server {
    root        /usr/local/nginx/html;
    index       index.html;
    rewrite     ^ $scheme://$request_uri permanent;
    # .... 

Save and close the file. Reload the nginx web-server, run:
# /usr/local/nginx/sbin/nginx -s reload

redirect vs permanent flag

The permanent flag redirect URL with http status code 301. It means that a page has permanently moved to a new location. This code is recommended by search engine giant Google:

301 redirects are particularly useful in the following circumstances:

  1. You’ve moved your site to a new domain, and you want to make the transition as seamless as possible.
  2. People access your site through several different URLs. If, for example, your home page can be reached in multiple ways – for instance,,, or – it’s a good idea to pick one of those URLs as your preferred (canonical) destination, and use 301 redirects to send traffic from the other URLs to your preferred URL. You can also use Webmaster Tools to set your preferred domain.
  3. You’re merging two websites and want to make sure that links to outdated URLs are redirected to the correct pages.

The redirect flag returns temporary redirect with http status code 302. It means that a page has moved temporarily to a new location. This code is not recommended for domain change.


Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Article Tags:
Article Categories:
How To

Comments are closed.