Tuesday, 2 August 2016

Debian - Nginx - Server Blocks (Virtual Hosts in Apache):

apt-get install nginx
/etc/init.d/nginx status
/usr/share/nginx/html               #default server block.                      
Step One — Set Up New Document Root Directories:
1. mkdir -p /var/www/example.com/html
    mkdir -p /var/www/test.com/html
2. chown -R $USER:$USER /var/www/example.com/html
#use the $USER environmental variable to substitute the user account that we are currently signed in on.
    chown -R $USER:$USER /var/www/test.com/html
3. chmod -R 755 /var/www
Step Two — Create Sample Pages for Each Site:
1. vim /var/www/example.com/html/index.html
<html>
    <head>
        <title>Welcome to Example.com!</title>
    </head>
    <body>
        <h1>Success!  The example.com server block is working!</h1>
    </body>
</html>
2. cp /var/www/example.com/html/index.html /var/www/test.com/html/
3. vim /var/www/test.com/html/index.html
<html>
    <head>
        <title>Welcome to Test.com!</title>
    </head>
    <body>
        <h1>Success!  The test.com server block is working!</h1>
    </body>
</html>
Step Three — Create Server Block Files for Each Domain
1. cp /etc/nginx/sites-available/default /etc/nginx/sites-available/example.com
2. vim /etc/nginx/sites-available/example.com
server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    access_log /var/log/nginx/www.example.com-access.log;
    error_log /var/log/nginx/www.example.com-error.log;

    root /var/www/example.com/html;
    index index.html index.htm;

    server_name example.com www.example.com;

    location / {
        try_files $uri $uri/ =404;
    }
}
#Server blocks for subdomain
server {
        listen 80;
        listen [::]:80;

        root /var/www/example.com/html;
        index index.html index.htm index.php;

        server_name sub2.example.com;
}

3. cp /etc/nginx/sites-available/example.com /etc/nginx/sites-available/test.com
4. vim /etc/nginx/sites-available/test.com
server {
    listen 80;
    listen [::]:80;

    access_log /var/log/nginx/www.test.com-access.log;
    error_log /var/log/nginx/www.test.com-error.log;

    root /var/www/test.com/html;
    index index.html index.htm;

    server_name test.com www.test.com;

    location / {
        try_files $uri $uri/ =404;
    }
}
Step Four — Enable your Server Blocks and Restart Nginx
1. ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
2. ln -s /etc/nginx/sites-available/test.com /etc/nginx/sites-enabled/
3. rm /etc/nginx/sites-enabled/default
4. vim /etc/nginx/nginx.conf
server_names_hash_bucket_size 64;                  #remove the comment
5. service nginx restart

Step Five — Test your Results
1. http://example.com
2. http://test.com