EN ES
Home > Web development > Servers Tutorials > Force Domain Use www Nginx

Force Domain Use www Nginx

Diego Cortés
Diego Cortés
September 2, 2016
Force Domain Use www Nginx

To force a domain to use www within NGINX, we must add the following block within our domain configuration file. In this example we will use the domain mydomain.com

On our server we look for the configuration file for our domain, usually you will find it in:

/etc/nginx/sites-avaliable/mydomain.com

We open this configuration file with sudo permissions, since we are modifying an nginx file as such in this case I will use nano since I am from the command line

sudo nano /etc/nginx/sites-avaliable/mydomain.com

Once the file is opened, to make it easy and fast we can paste the following code at the beginning of our configuration file:

server {
    listen 80;
    server_name mydomain.com;
    return 301 http://www.mydomain.com$request_uri;
}

We can see that we are doing a permanent 301 redirect, this is important for positioning purposes.

An example of how it would look like:

server {
    listen 80;
    server_name mydomain.com;
    return 301 http://www.mydomain.com$request_uri;
}

server {
    server_name www.mydomain.com;
    root /home/user/mydomain.com/public/;
    index index.php index.html;

}

Remember that the server block below is just a reference to what you would have, the reference path to root may change on your server, needless to say that the block we added can be added in a new file and simply called within it with an include so that our configuration is more organized.

The root path may change on your server

IMPORTANT: in the second server block, leave only the domain with www, otherwise in the latest versions of NGINX 1.08 you will get the error.

I hope it helps more than one 😀

Diego Cortés
Diego Cortés
Full Stack Developer, SEO Specialist with Expertise in Laravel & Vue.js and 3D Generalist

Categories

Page loaded in 41.89 ms