How To Set Up Nginx Server Blocks on CentOS 7

Nginx is a powerful and efficient web server that is widely used to serve web content and handle various tasks, including reverse proxying, load balancing, and more. One of its key features is the ability to host multiple websites or applications on a single server using server blocks, also known as virtual hosts. In this guide, we’ll walk you through the process of setting up Nginx server blocks on CentOS 7.

Prerequisites:

Before you start, make sure you have a CentOS 7 server with Nginx installed. You can install Nginx using the following commands:

sudo yum install epel-release sudo yum install nginx sudo systemctl start nginx sudo systemctl enable nginx

Step 1: Create the Directory Structure

It’s a good practice to organize your website or application files within a specific directory structure. Create a directory for your website or application, replacing “example.com” with your domain or application name:

sudo mkdir -p /var/www/example.com/html

Step 2: Set Permissions

Ensure that the Nginx user (usually “nginx”) has the necessary permissions to access the website or application files:

sudo chown -R nginx:nginx /var/www/example.com sudo chmod -R 755 /var/www

Step 3: Create an Nginx Server Block Configuration File

Navigate to the Nginx configuration directory and create a new server block configuration file for your site:

sudo nano /etc/nginx/conf.d/example.com.conf

Add the following basic configuration, adjusting it according to your needs:

server { listen 80; server_name example.com www.example.com; root /var/www/example.com/html; index index.html; location / { try_files $uri $uri/ =404; } error_page 404 /404.html; error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } }

Save the file and exit the text editor.

Step 4: Test Nginx Configuration

Before applying the changes, test the Nginx configuration to ensure there are no syntax errors:

sudo nginx -t

If the test is successful, reload Nginx to apply the changes:

sudo systemctl reload nginx

Step 5: Add DNS Records

Update your domain’s DNS records to point to the server’s IP address.

Step 6: Verify Your Configuration

Open a web browser and navigate to your domain (e.g., http://example.com). If everything is set up correctly, you should see the default Nginx welcome page or your custom content.

Conclusion:

Setting up Nginx server blocks on CentOS 7 allows you to host multiple websites or applications on a single server efficiently. By following this step-by-step guide, you can organize your server’s configuration and streamline the process of managing multiple sites.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

write for us
adbanner