How to redirect Wordpress traffic with Nginx

Recently I moved my Wordpress blog to Ghost, also changing to the current domain and I'm going to show how I redirected the Wordpress traffic with Nginx without losing SEO.

Keys

  • Keep working all URLs
  • Permanent redirects

My case

  • I have different domains, I moved from davidburgosonline.com to davidburgos.blog
  • My Wordpress URL config was:
/category/year/post-slug
  • and in Ghost is:
/post-slug

Keep in mind you must not change any Wordpress post's URL.

Redirect Wordpress traffic with Nginx

Edit your Nginx config file, usually in /etc/nginx/nginx.conf:

  • I added a server block
  • Listening port 80 at the previous domain olddomain.com
  • Your olddomain.com DNS should point to the newdomain.com server
  • For any location matching the Wordpress URL format, redirect to the new domain rewriting the slug.

Code example:

server {
    listen 80;
    server_name olddomain.com;

    location / {
        rewrite "\w{2,}/\d{4}/(.*)$" https://newdomain.com/$1 permanent;
        rewrite ^/(.*)$ https://newdomain.com/$1 permanent;
    }
}
  • First rewrite redirects permanently any post, according to the post slug config.
  • Second rewrite redirects any URL to the new domain

One more thing

In case your Wordpress URL format is just /year/slug the rewrite line would be:

        rewrite "\d{4}/(.*)$" https://newdomain.com/$1 permanent;

Keep in mind is just a regular expression, so feel free to change it in order to fit your case.

Don't forget

You should restart Nginx to apply the changes

sudo service nginx restart

If this article helped you, share it :)

David Burgos

Read more posts by this author.