Join our Telegram: @serverrental_wiki | BTC Analysis | Trading Signals | Telegraph
Installing and Configuring Nginx
This article provides a comprehensive guide to installing and configuring Nginx, a powerful and high-performance web server, on a Linux system. We'll cover everything from initial installation to advanced topics like virtual hosts, SSL certificates, reverse proxy setups, and performance tuning. This guide is suitable for beginners to intermediate system administrators looking to leverage Nginx for their web hosting needs.
Prerequisites
Before you begin, ensure you have the following:
- A server running a modern Linux distribution (e.g., Ubuntu 20.04 LTS, Debian 10, CentOS 8). For reliable performance, consider dedicated servers available at PowerVPS with full root access.
- Root or sudo privileges on your server.
- Basic familiarity with the Linux command line.
- A domain name (e.g., `example.com`) pointing to your server's public IP address.
Installing Nginx
Nginx is available in the default repositories of most Linux distributions, making installation straightforward.
On Debian/Ubuntu
1. **Update package lists:**
```bash sudo apt update ``` This command synchronizes your local package index with the remote repositories, ensuring you install the latest available version.
2. **Install Nginx:**
```bash sudo apt install nginx ``` This installs the Nginx web server and its dependencies.
3. **Verify installation and status:**
```bash sudo systemctl status nginx ``` You should see output indicating that Nginx is `active (running)`. Press `q` to exit the status view.
Expected Output Snippet:
● nginx.service - A high performance web server and a reverse proxy server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: active (running) since Mon 2023-10-27 10:00:00 UTC; 1min 30s ago
Docs: man:nginx(8)
Main PID: 12345 (nginx)
Tasks: 2 (limit: 1153)
Memory: 3.5M
CPU: 50ms
CGroup: /system.slice/nginx.service
├─12345 /usr/sbin/nginx -g daemon on; master_process=on;
└─12346 nginx: worker process
4. **Configure firewall (if using UFW):**
If you are using the Uncomplicated Firewall (UFW), you need to allow Nginx traffic. ```bash sudo ufw allow 'Nginx Full' sudo ufw enable ``` The 'Nginx Full' profile allows both HTTP (port 80) and HTTPS (port 443) traffic.
On CentOS/RHEL
1. **Install EPEL repository (if not already present):**
```bash sudo dnf install epel-release -y ``` The Extra Packages for Enterprise Linux (EPEL) repository provides additional packages, including newer versions of Nginx.
2. **Install Nginx:**
```bash sudo dnf install nginx -y ```
3. **Start and enable Nginx:**
```bash sudo systemctl start nginx sudo systemctl enable nginx ``` `start` begins the Nginx service immediately, while `enable` ensures it starts automatically on boot.
4. **Configure firewall (if using firewalld):**
```bash sudo firewall-cmd --permanent --add-service=http sudo firewall-cmd --permanent --add-service=https sudo firewall-cmd --reload ``` This opens ports 80 and 443 for web traffic.
Testing the Installation
Open your web browser and navigate to your server's IP address (e.g., `http://your_server_ip`). You should see the default Nginx welcome page. This confirms Nginx is installed and running correctly.
Configuring Virtual Hosts
Virtual hosts (also known as server blocks in Nginx) allow you to host multiple websites on a single server. Each virtual host is configured in its own file.
1. **Create a directory for your website files:**
Replace `example.com` with your domain name. ```bash sudo mkdir -p /var/www/example.com/html ``` The `-p` flag creates parent directories if they don't exist.
2. **Create a sample index file:**
```bash
sudo nano /var/www/example.com/html/index.html
```
Add some basic HTML content:
```html
<!DOCTYPE html>
<html>
<head>
<title>Welcome to example.com!</title>
</head>
<body>
Success! The example.com virtual host is working!
</body> </html> ``` Save and exit (Ctrl+X, Y, Enter in nano).
3. **Set ownership and permissions:**
Ensure Nginx can read your website files. ```bash sudo chown -R $USER:$USER /var/www/example.com/html sudo chmod -R 755 /var/www/example.com/html ``` This gives ownership to your current user for easy file management, and sets read/execute permissions for others.
4. **Create an Nginx server block configuration file:**
Configuration files for Nginx virtual hosts are typically stored in `/etc/nginx/sites-available/` and then symlinked to `/etc/nginx/sites-enabled/`.
```bash
sudo nano /etc/nginx/sites-available/example.com
```
Add the following configuration:
```nginx
server {
listen 80;
listen [::]:80;
root /var/www/example.com/html;
index index.html index.htm index.nginx-debian.html;
server_name example.com www.example.com;
location / {
try_files $uri $uri/ =404;
}
}
```
* `listen 80;`: Tells Nginx to listen on port 80 for IPv4 connections.
* `listen [::]:80;`: Listens on port 80 for IPv6 connections.
* `root /var/www/example.com/html;`: Specifies the document root for this server block.
* `index index.html ...;`: Defines the order of files Nginx will look for when a directory is requested.
* `server_name example.com www.example.com;`: Matches requests for these domain names.
* `location / { ... }`: Handles requests for any URI. `try_files` attempts to serve the requested file, then a directory index, or returns a 404 error.
5. **Enable the server block:**
Create a symbolic link from `sites-available` to `sites-enabled`. ```bash sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ ```
6. **Remove the default configuration (optional but recommended):**
To avoid conflicts, it's good practice to remove the default Nginx welcome page configuration. ```bash sudo rm /etc/nginx/sites-enabled/default ```
7. **Test Nginx configuration:**
Always test your Nginx configuration before reloading the service. ```bash sudo nginx -t ``` Expected Output:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
8. **Reload Nginx:**
Apply the changes. ```bash sudo systemctl reload nginx ```
Now, when you visit `http://example.com` in your browser, you should see the "Success!" message from your `index.html` file.
Securing with SSL/TLS (HTTPS)
To secure your website and enable HTTPS, you'll need an SSL/TLS certificate. Let's Encrypt provides free certificates.
Installing Certbot
Certbot is a tool that automates the process of obtaining and renewing Let's Encrypt certificates.
On Ubuntu/Debian
1. **Install Certbot and the Nginx plugin:**
```bash sudo apt install certbot python3-certbot-nginx -y ```
2. **Obtain and install the certificate:**
Replace `example.com` and `www.example.com` with your actual domain names. ```bash sudo certbot --nginx -d example.com -d www.example.com ``` Certbot will guide you through the process, asking for your email address and agreeing to terms. It will then automatically modify your Nginx configuration to use the new certificate and set up automatic renewal.
On CentOS/RHEL
1. **Install Certbot:**
```bash sudo dnf install certbot python3-certbot-nginx -y ```
2. **Obtain and install the certificate:**
```bash sudo certbot --nginx -d example.com -d www.example.com ``` Follow the prompts as described above.
After running Certbot, it will typically ask if you want to redirect HTTP traffic to HTTPS. It's recommended to choose the redirect option for enhanced security.
Testing SSL
Visit your website using `https://example.com`. Your browser should show a padlock icon, indicating a secure connection. You can also use online SSL checker tools to verify your configuration.
Configuring Nginx as a Reverse Proxy
A reverse proxy sits in front of one or more backend servers, forwarding client requests to them. This is useful for load balancing, security, and serving different applications from the same domain.
Let's assume you have a backend application running on `http://localhost:3000`.
1. **Edit your Nginx server block configuration:**
```bash sudo nano /etc/nginx/sites-available/example.com ```
2. **Modify the `location` block:**
Replace the existing `location / { ... }` block with the following:
```nginx
location / {
proxy_pass http://localhost:3000;
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;
}
```
* `proxy_pass http://localhost:3000;`: Forwards requests to your backend application.
* `proxy_set_header ...`: These directives pass important information about the original client request to the backend application, which might otherwise only see the proxy's IP address.
3. **Test and reload Nginx:**
```bash sudo nginx -t sudo systemctl reload nginx ```
Now, when you access `http://example.com` (or `https://example.com` if SSL is configured), Nginx will forward the request to your backend application.
Performance Tuning
Nginx is known for its performance. Here are some common tuning parameters:
1. **Worker Processes:**
Nginx can use multiple worker processes to handle requests concurrently. It's generally recommended to set this to the number of CPU cores your server has. Edit the main Nginx configuration file: ```bash sudo nano /etc/nginx/nginx.conf ``` Find the `worker_processes` directive and set it: ```nginx worker_processes auto; # Or set to the number of CPU cores ``` `auto` is often sufficient, letting Nginx determine the optimal number.
2. **Worker Connections:**
This directive specifies the maximum number of simultaneous connections that each worker process can handle.
Inside the `events` block in `nginx.conf`:
```nginx
events {
worker_connections 1024; # Adjust based on server resources and expected load
}
```
A common starting point is 1024. For high-traffic sites, you might need to increase this and also adjust system limits (e.g., `/etc/security/limits.conf`).
3. **Keepalive Timeout:**
Keeps a connection open for a specified time, reducing the overhead of establishing new connections.
Inside the `http` block in `nginx.conf`:
```nginx
http {
# ... other http settings
keepalive_timeout 65;
keepalive_requests 1000;
}
```
4. **Gzip Compression:**
Compresses responses before sending them to the client, reducing bandwidth usage and improving load times.
Inside the `http` block in `nginx.conf`:
```nginx
http {
# ... other http settings
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
}
```
5. **Browser Caching:**
Instructs the browser to cache static assets, so they don't need to be re-downloaded on subsequent visits.
Add this to your server block configuration (`/etc/nginx/sites-available/example.com`):
```nginx
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public";
}
```
After making any changes to `nginx.conf`, remember to test and reload Nginx: ```bash sudo nginx -t sudo systemctl reload nginx ```
Troubleshooting
- **502 Bad Gateway:** Often indicates that Nginx cannot reach the backend application (e.g., a reverse proxy issue). Check if your backend application is running and accessible from Nginx. Verify `proxy_pass` directive and firewall rules.
- **403 Forbidden:** Usually means Nginx doesn't have permission to read the requested file or directory. Check file permissions (`chmod`) and ownership (`chown`) for your web root.
- **404 Not Found:** The requested file does not exist. Double-check the `root` directive in your server block and ensure the file path is correct. Also, verify `try_files` directive.
- **Nginx Fails to Start/Reload:** Run `sudo nginx -t` to check for syntax errors in your configuration files. The output will point to the problematic line. Common issues include typos, missing semicolons, or incorrect directives.
- **SSL Certificate Errors:** Ensure your domain name is correctly listed in the `server_name` directive and that Certbot successfully modified the configuration. Check the certificate expiration date.