Remove or add www. with nginx
This blog post was originally published a little while ago. Please consider that it may no longer be relevant or even accurate.
I recently moved my blog off shared hosting (and off Wardrobe CMS) to use Laravel Forge instead. As part of this change I had to drop the
.htaccess file and the lenghty additions to it from HTML 5 Boilerplate Apache Configuration and get more familiar with Nginx. Luckily, there is a similar boilerplate for Nginx.
I'm a big fan of prefixing
www. to my sites, and so I wanted to redirect any request without that prefix to the proper version - a 301 redirect so that Google would only index the right site and all links would come to the right place. To do this I just had to edit the Nginx configuration in Laravel Forge and that isn't actually too hard.
First, click on your server and then click into manage the site you want to perform a redirect for. At the bottom there is a little edit dropdown which opens up to let you edit your Nginx configuration. Once the modal pops open you can prefix your site configuration.
Of course, if you want to do the other and redirect to remove the
www. you can just switch those settings around.
And don't forget to replace the server name with your own site!