Last Updated: February 25, 2016
· geetotes

Force www for nginx websites

So I'm still learning nginx, so this may not be a protip, but anyway.

I have domain example.com and I want all requests to re-direct to www.example.com. I'll need to set up two rules in nginx. The first is a simple rule to catch the non-www and redirect it.

server {
server_name example.com;
rewrite ^(.*)$ $scheme://www.example.com;

Why no nginx equilavent to httpd's ServerAlias? I don't know. I'm crying: T_T

However, the $scheme built-in variable is hella cool

Now let's set up a rule to catch www.example.com and we're done
server_name www.example.com;
root /var/www/example.com;
#more directives, etc, etc

And the rewrite is complete!