Nginx: redirect non-www to www address‏

Problem (example):
I want to redirect all user request whether it is from or to . (This method usually used as one of SEO effort).
Nginx didn’t know .htaccess

nginx has it’s own rewrite module and method.

This is an example server block that will solve the problem:

    server {
        listen 80;

        # this is the nginx redirection from non-www to www example
        if ($host = '') {
            rewrite ^(.*)$1 permanent;

        # bla bla bla bla ... other settings such as root, index, location.. etc.

As you can see, those server block will handle request that has and in its HTTP_HOST.
The if block will check if the HTTP_HOST is exact match to ‘’, if it’s true then user will be redirected to ‘’ and the same server block will handle this request. Quite simple isn’t it?

Notes: Of course, now, did not use nginx as it’s web server after I noticed the server load is sky high when using nginx compared to when using apache2

Leave a Comment

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>