Redirecting non-www to www with Nginx

Submitted by slava on 24 January 2016

The default .htaccess file that is bundled with Drupal works pretty well on servers with Apache. However, if your server uses Nginx to serve site pages to visitors you will quickly find that it knows nothing about .htaccess files and never loads them. So, redirecting users from the non-www domain to the www one is a bit more complex there.

You are to edit your website configuration (on my DigitalOcean server it is located at /etc/nginx/sites-available/drupal) and add the following section at the top of the file:

server {
    listen       80;
    server_name  YOUR_DOMAIN.com;
    return       301 http://www.YOUR_DOMAIN.com$request_uri;
}

Then edit the original "server" section (that now is placed lower in the file) and add the following line below "listen" directives:

server {
    listen ...
    listen ...
    server_name  www.YOUR_DOMAIN.com;
    ...
}

Now you should restart Nginx in the Linux console to make the changes take effect:

sudo service nginx restart

This should be enough.

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
By submitting this form, you accept the Mollom privacy policy.