How to Install Nginx on Linux, Set Up Server Blocks, and Configure Reverse Proxy
Nginx is a powerful and popular web server that is widely used to serve static content, reverse proxy, and more. In this guide, we'll walk through the steps to install Nginx and setting it up as a reverse proxy.
Step 1: Update Package Repository
Before installing any software, make sure your package repository is up-to-date. Use the appropriate command for your Linux distribution:
For Debian/Ubuntu:
sudo apt update
For Red Hat/CentOS:
sudo yum update
Step 2: Install Nginx
Install Nginx using your distribution's package manager:
For Debian/Ubuntu:
sudo apt install nginx
For Red Hat/CentOS:
sudo yum install nginx
Step 3: Start and Enable Nginx
Start Nginx:
sudo systemctl start nginx
Enable Nginx to start on boot:
sudo systemctl enable nginx
Step 4: Configure Server Blocks
Create Configuration Files for Each Site
Create a configuration file for each of your websites in the /etc/nginx/sites-available/
directory. For example:
sudo nano /etc/nginx/sites-available/example.com
Add the following basic server block configuration. Replace example.com
with your actual domain name and adjust the proxy_pass settings based on your backend server:
server {
listen 80;
server_name example.com www.example.com;
location / {
proxy_pass http://localhost:8080; # Change this to your backend server
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# Additional server block configuration...
}
Step 5: Create Symbolic Links
Create symbolic links for each configuration file in the sites-enabled
directory:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
Repeat this step for each server block.
Step 6: Test Nginx Configuration
Check for syntax errors:
sudo nginx -t
Step 7: Restart Nginx
If there are no errors, restart Nginx:
sudo systemctl restart nginx
Step 8: Adjust Firewall Rules (if applicable)
If you're using a firewall, update the rules:
sudo ufw allow 'Nginx Full'
Step 9: Test Your Configuration
Open your web browser and navigate to each of your domain names. Ensure that the server blocks are working correctly.
Congratulations! You've successfully installed Nginx on Linux and configured it as a reverse proxy. Customize the configuration based on your specific needs and backend server setup.