NGINX 301 Redirects

NGINX is a great lightweight webserver, and the one this blog runs on. Having made many iterations including merging other blogs into it, and removing posts and entire sections, I’ve had to create a number of redirects for both user experience and search engine indexing. This post will show you how to create a variety of 301 Permanent redirects in your NGINX config file.

Avoid redirecting pages, and keep the url the same when rebuilding a site when you can, but if you do need to redirect domains, directories, or pages on an NGINX server this will help.

NGINX Domain Redirects

For new websites, having the www before your domain is really not needed. Here is how to redirect the www version of your website to the cleaner, non-www version.

WWW to Non-WWW Redirect

server   {
   server_name www.domain.com;
   rewrite  ^/(.*)$  http://domain.com/$1 permanent;
}

Non-WWW to WWW Redirect

Alternately, if your site has been around a long time, and used the www version, you can make sure users are redirected to the www version.

server   {
   server_name domain.com;
   rewrite  ^/(.*)$  http://www.domain.com/$1 permanent;
}

NGINX Directory Redirect

You may need to redirect an entire directory of pages to another if you rename it. I tend to change the structure of this site quite often, so I’ve got a couple of them in my config file.

This directive goes within the main server block of your sites NGINX config.

   if ( $request_filename ~ old-directory/.+ ) {
       rewrite ^(.*) http://domain.com/new-directory/$1 permanent;
   }

If you are redirecting to top level pages on your site, use this:

   if ( $request_filename ~ old-directory/.+ ) {
       rewrite ^(.*) http://domain.com/$1 permanent;
   }

NGINX Single Page Redirect

When you rebuild a website, it’s common to remove pages, or rename them. If the page has links from other website, you don’t want users who click the link to land on a 404 Error page. The best thing to do in this case is to send the user to the next most useful page.

Use this directive in the server block to redirect single pages.

   if ( $request_filename ~ old-page/ ) {
      rewrite ^ http://jeffsebring.com/next-best-page/? permanent;
   }