Redirect non-www to www on Nginx server (+WordPress)

Posted on September 6, 2014 in Web Dev

Implementing a sitewide 301 isn’t particularly difficult. However, I kept hitting a redirect loop and just couldn’t figure out why. The problem was the URL as defined by WordPress was the non-www version, and not my desired www version. So, basically the server was redirecting from non-www to www, and then WordPress’ redirect was going from www to non-www, and thus the loop was formed.

Sitewide Nginx 301 from non-www to www

Navigate to your server block file. Depending on your method of setting up the server, this will either be at:


Or at

/etc/nginx/sites-available/<site name>

Where <site name> is the name of the file containing your server block (best practice says that this should be your site name).

We need to define a separate server block for the non-www version as well as the www version. For example:

server {
    rewrite ^(.*)$1 permanent;

server {
    #The rest of your configuration goes here#

Make sure you replace “” with your actual domain, and that the rest of your configuration is in tact.

There’s a great Stack Overflow thread on the topic of NGinx 301s here:

The WordPress Issue

Something that is very easily overlooked (well, in my experience anyway) is the sheer amount of stuff that WordPress does for you. This is great at times, but it can make debugging a nightmare. The WordPress installation is the last place I thought to look when dealing with what appeared to be a server-specific issue.

The problem was that the “WordPress Address (URL)” and “Site Address (URL)” settings were both still pointing to the non-www version. Simply change these two settings to your desired version, press save, and you should be good to go.

Note that if changing these two settings doesn’t work, then remember to check your wp_config.php file to make sure that these aren’t hardcoded into the installation. The above settings are saved to the database, whereas a hardcoded Site Address will take priority over the database call.

Leave a comment

Was this helpful? Did I miss something? Do you have a question? Get in touch, or tell me below.