How to Install Nginx and Setup Server Blocks

How to Setup Server Blocks NGINX

Explain How to Setup Server Blocks NGINX

Learn how to setup server blocks in NGINX with this step-by-step guide. Perfect for beginners!, After having previously installed nginx on your vps, this time we’re going to configure for the server blocks that exist on the Nginx, so that the website or application can be exposed to the public. Don’t forget to first log in to the vps using a non-root user.

Condition

Before you start, make sure you have installed nginx in vps and already have an Ubuntu Server operating system of course, if you haven’t, I recommend buying it here Niagahoster. They have many cheap servers like VPS, Cloud and also Web Hosting.

Step 1 – Setting Server Blocks

By default after nginx installed, it will create a folder called html in /var/www/html. But i recommend you to remove the html folder and use as your app or web name like this:

sudo rm -R /var/www/html    #remove html folder
sudo mkdir /var/www/<your_app_or_web_name> #it can be my_apps or my_webs

Next we will make a site server blocks inside nginx configuration:

sudo nano /etc/nginx/sites-available/<your_app_or_web_name>

Copy this to your server blocks:

server {
        listen 80;
        listen [::]:80;

        root /var/www/your_app_or_web_name;
        index index.html index.htm index.nginx-debian.html;

        server_name your_domain www.your_domain;

        location / {
                try_files $uri $uri/ =404;
        }
}

Save it by doing ctrl+o then ctrl+x.

Do not forget to link the sites-available into sites-enabled and restart your nginx server, by doing this:

sudo ln -s /etc/nginx/sites-available/<your_app_or_web_name> /etc/nginx/sites-enabled/

sudo nginx -t
sudo service nginx restart

Step 2 – Setup Ownership App Folder

Remember to do this after setup the server blocks, because your app folder is still in root ownership and you login with non-root user. Get inside of your folder in /var/www/<your_app_or_web_name>, and write this:

sudo chown -R $USER /var/www/<your_app_or_web_name>

#give permissions to your app or web folder
sudo chmod -R 755 /var/www/<your_app_or_web_name>

Awesome!, you are succesfully setup your server blocks. You can try to your browser, but if you still get stuck please read again our article before, maybe there is some failure when installing nginx here How to Install Nginx on Ubuntu 22.04. Another step is we will give some tutorial about to integrating Git Project to your VPS.

Comments

No comments yet. Why don’t you start the discussion?

    Leave a Reply

    Your email address will not be published. Required fields are marked *