How To Redirect non-www To www And Vice Versa with Nginx

 ·  · 

1 Redirect non-www To www

Assume that you already have your Nginx domain configured with www as follows.

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    server_name www.YOURDOMAIN.com;


    root /YOUR_WEB_FOLDER;
    index index.php index.html index.htm;

    server_name www.YOURDOMAIN.com;

    # ...
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    ssl on;

    server_name www.YOURDOMAIN.com;

    root /YOUR_WEB_FOLDER;
    index index.php index.html index.htm;

    ssl_certificate /YOUR_SSL_FILE_FOLDER/nginx.crt;
    ssl_certificate_key /YOUR_SSL_FILE_FOLDER/nginx.key;

    # ...
}

In order to redirect non-www access to www, add a new server block in your Nginx domain configuration file above.

server {
    listen 80;
    listen [::]:80;

    server_name YOURDOMAIN.com;

    # comment or remove following four lines if you don't have https
    listen 443 ssl;
    listen [::]:443 ssl;
    ssl_certificate /YOUR_SSL_FILE_FOLDER/nginx.crt;
    ssl_certificate_key /YOUR_SSL_FILE_FOLDER/nginx.key;

    return 301 $scheme://www.YOURDOMAIN.com$request_uri;
}

Check and test the edited configuration file.

$ sudo nginx -t

Finally, reload or restart nginx.

$ sudo nginx reload

# or restart nginx in Ubuntu
$ sudo service nginx restart

 

2 Redirect www To non-www

Similarly, assume that you have following non-www configurations already.

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;


    root /YOUR_WEB_FOLDER;
    index index.php index.html index.htm;

    server_name YOURDOMAIN.com;

    # ...
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    ssl on;

    server_name YOURDOMAIN.com;

    root /YOUR_WEB_FOLDER;
    index index.php index.html index.htm;

    ssl_certificate /YOUR_SSL_FILE_FOLDER/nginx.crt;
    ssl_certificate_key /YOUR_SSL_FILE_FOLDER/nginx.key;

    # ...
}

To redirect www access to non-www, add a new server block with following lines.

server {
    listen 80;
    listen [::]:80;

    server_name www.YOURDOMAIN.com;

    # comment or remove following four lines if you don't have https
    listen 443 ssl;
    listen [::]:443 ssl;
    ssl_certificate /YOUR_SSL_FILE_FOLDER/nginx.crt;
    ssl_certificate_key /YOUR_SSL_FILE_FOLDER/nginx.key;

    return 301 $scheme://YOURDOMAIN.com$request_uri;
}

Finally, test and then reload or restart Nginx.

$ sudo nginx -t

$ sudo nginx reload

# or restart nginx in Ubuntu
$ sudo service nginx restart