how to force www to naked url

May 18, 2017 1.8k views
Nginx Ubuntu 16.04

I have the url mysite.com, everytime i press enter it redirects to www.mysite.com, I don’t want it to show the www part at all.

1 Answer

@ariziragoran

You’ll want to make sure that you’ve setup a redirect for the www variant of your domain.

For example, if your domain is example.com, we’d use something such as:

server {
    listen 80;
    listen [::]:80;
    server_name www.example.com;

    return 301 https://$host$request_uri;
}

server {
    listen 80;
    listen [::]:80;
    server_name example.com;

    ....
    ....
    ....
    ....
}

The first server block handles the redirection from www to your base domain. The second server block is where you main configuration would be.

  • www.example.com ends up in a google search now rather than attempting to redirect. However example dot com is now naked. So fixed one thing but broke another.

    server {
            listen 80;
            listen [::]:80;
            server_name www.example.com;
    
            return 301 http://$host$request_uri;
    }
    
    server {
            listen 80;
            listen [::]:80;
    
            root /var/www/example.com/html;
    
            index index.html index.htm index.nginx-debian.html;
    
            server_name example.com;
    
            location / {
                    try_files $uri $uri/ =404;
            }
    }
    
    • http://$host$request_uri;
      

      doesn’t work, i had to use

      return 301 http://example.com 
      

      Because right now, your suggested change results in The page isn’t redirecting properly

      • @ariziragoran

        In some cases you may need to hard-code the redirect, as you have done, in others either $host or $server_name will work – both are valid.

        Since you’re removing the www in this case, I’d keep the hard-coded redirect in place since using the others may not work as expected.

Have another answer? Share your knowledge.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!