How To make Nginx force www

Nginx is a great speedy web server, and config files are quite a breeze. Nginx doesn’t use .htaccess files like Apache, but forcing www is as simple as adding another server instance into the config file.

Below is a short snippet on forcing www to your domain name.

/etc/nginx/sites-available/andrewklau.com

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

server {  
    server_name www.andrewklau.com;
    ## YOUR OTHER CONFIGS HERE ##
}

Alternatively if you want to force non-www

/etc/nginx/sites-available/andrewklau.com

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

server {  
    server_name andrewklau.com;
    ## YOUR OTHER CONFIGS HERE ##
}

Don’t forget, if you’re using a CMS such as WordPress remember to update the settings in there first or it’ll be sending you in an infinite redirect loop!

comments powered by Disqus