How to Install Nginx on Debian 12, 11 or 10

Nginx is a powerful web server known for its high performance and low resource consumption. Originally designed to handle the C10k problem, it excels in serving static content, load balancing, and reverse proxying. Combining Nginx with Debian, known for its stability and security, results in a robust and reliable server environment.

Key Features of Nginx:

  • High Performance: Efficiently handles multiple concurrent connections.
  • Low Resource Usage: Optimized to run with minimal memory and CPU.
  • Load Balancing: Distributes traffic across multiple servers for improved performance.
  • Reverse Proxying: Forwards client requests to backend servers seamlessly.
  • Static Content Handling: Serves static files quickly and efficiently.
  • Security Features: Supports SSL/TLS for encrypted communications.
  • Flexibility: Supports protocols like HTTP, HTTPS, SMTP, POP3, and IMAP.

Benefits of Combining Nginx with Debian:

  • Stability: Debian’s reputation for stability ensures your server remains reliable.
  • Security: Debian’s robust security measures protect your Nginx server from vulnerabilities.
  • Ease of Use: Debian’s package management system simplifies installing and maintaining Nginx.
  • Community Support: Nginx and Debian have strong communities providing extensive resources and support.

Transitioning into the setup, you’ll find that Debian’s stability pairs perfectly with Nginx’s efficiency, creating an ideal environment for your web applications. Let’s delve into the steps required to install and configure Nginx on a Debian server.

Preparing Your System Before Nginx Installation

Ensure your system is updated before installing Nginx. This prevents potential conflicts during the installation and reduces the risk of compatibility issues and security vulnerabilities.

To update your system packages, run the following:

sudo apt update && sudo apt upgrade

This command fetches the list of available updates (via apt update) and then upgrades the current software packages to their latest versions (using apt upgrade).

Install NGINX’ Web Server’ standard

By default, NGINX is available in the Debian repositories. This makes the installation process straightforward.

Run the following command to install nginx:

sudo apt install nginx

The apt install command tells APT package handling utility (a part of the Debian system) to install the NGINX package.

Optional: Install the NGINX-Full Version

NGINX offers a nginx-full version with additional modules not found in the standard version. If you require more functionality, install the nginx-full version:

sudo apt install nginx-full

Optional: Install the NGINX-Extras Version

For an even broader feature set, consider the nginx-extras version. To install:

sudo apt install nginx-extras

Verifying the NGINX Installation

After installation, ensure NGINX is running correctly.

Check the NGINX service status with the following:

systemctl status nginx

NGINX operates correctly if the output shows “active (running).” If not, the output will detail the error for troubleshooting.

If NGINX isn’t enabled, use:

sudo systemctl enable nginx --now

Configure UFW Firewall For Nginx

UFW, or Uncomplicated Firewall, provides an easy-to-use interface for managing iptables firewall rules. It’s not installed on Debian by default, but you can get it from the default repositories. If your server has public access, you should set up UFW rules for security.

Install UFW Firewall

If UFW isn’t already installed on your system, you can do so by executing the following command:

sudo apt install ufw

Enable UFW Firewall

Once the installation is complete, you can enable UFW by running the following command:

sudo ufw enable

UFW’s default settings block all incoming connections and allow all outgoing ones. This means it stops unsolicited system access but lets your system reach the outside world.

Listing Installed Applications

UFW uses application profiles, which are sets of rules for specific applications. To see installed applications that have UFW profiles, run:

sudo ufw app list

Configuring UFW Rules for NGINX

Depending on your needs, you can configure UFW to let NGINX connections through HTTP (Port 80), HTTPS (Port 443), or both.

For HTTP (Port 80) only:

sudo ufw allow 'Nginx HTTP'

HTTPS (Port 443) only:

sudo ufw allow 'Nginx HTTPS'

Both HTTP and HTTPS:

sudo ufw allow 'Nginx Full'

Verifying Firewall Rules

To confirm your rules are in place, check the active firewall rules:

sudo ufw status

Testing NGINX Configuration

After setting up UFW, ensure you can see the NGINX landing page. In your browser, go to your server’s IP address:

http://your_server_ip

Or, for local setups:

http://localhost

Suppose you see the NGINX default page; your configuration works. This ends the firewall setup for NGINX on Debian.

Create NGINX Server Blocks

Like Apache’s virtual hosts, NGINX server blocks let you host multiple domains from one server. Each domain has its configuration settings. For this guide, replace “example.com” with your actual domain name.

Create a Directory for Your Domain

Set up a directory for your domain. This directory will store your website’s files:

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

Assign Ownership to the Nginx Directory

Assign directory ownership to the “www-data” user and group, which NGINX usually uses:

sudo chown -R www-data:www-data /var/www/example.com/

Create a Nginx Test HTML Page

Create a test HTML page in your domain directory to confirm your NGINX setup:

sudo nano /var/www/example.com/index.html

Add the following HTML code:

<html>
 <head>
  <title>Welcome to Example.com</title>
 </head>
 <body>
   <h1>Success! The NGINX server block is working!</h1>
 </body>
</html>

After you’ve pasted the code into the nano editor, press CTRL+O to save the changes and then CTRL+X to exit the editor.

Create an NGINX Server Block For Test Page

Set up a server block for your website:

sudo nano /etc/nginx/sites-available/example.com.conf

Add the following configuration:

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

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

 server_name example.com www.example.com;

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

This configuration tells NGINX to listen for incoming connections on port 80 for both example.com and www.example.com. Be sure to replace the root directive with the directory path you created earlier.

Enable the NGINX Server Block via symlink

Enable your server block by creating a symbolic link from the sites-available directory to the sites-enabled directory:

sudo ln -s /etc/nginx/sites-available/example.com.conf /etc/nginx/sites-enabled/

Final Configuration & Test Run

Lastly, we’ll edit the default NGINX configuration file and perform a test run to ensure everything works as expected.

Editing the NGINX Configuration File

Open the nginx.conf file:

sudo nano /etc/nginx/nginx.conf

Look for the line server_names_hash_bucket_size 64; within the http {} block and uncomment it.

This directive allows NGINX to handle long domain names and more significant numbers of server names by allocating more memory for this purpose. However, be cautious not to set this value too high, as it might consume more memory than needed.

Save the changes and exit the editor by pressing CTRL+O and CTRL+X.

Test Your NGINX Configuration

Before you go ahead and restart NGINX, it’s a good practice to verify that your configuration syntax is correct. Run the following command to initiate a test run:

sudo nginx -t

If your configuration is correct, you’ll see this output:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

These messages indicate that your NGINX configuration has been successfully validated.

Verifying Your Server Block

To ensure your server block functions appropriately, open your domain in a web browser. You should see the test page confirming your server block is active.

Additional Nginx Commands

Enhancing File Security in Your Webserver

Security for files and folders on your web server is paramount. Avoid overly permissive access rights. Use these commands to set correct permissions for all files and directories in your webroot.

Remember to replace /var/www/example.com/ with your webroot path:

sudo find /var/www/example.com/ -type d -exec chmod 755 "{}" \;
sudo find /var/www/example.com/ -type f -exec chmod 644 "{}" \;

These commands set read and execute permissions for directories and read-write permissions for files for the owner. Groups and others get read-only access. Adjust these permissions as your application demands.

Nginx Security with Let’s Encrypt Free SSL Certificate

Using HTTPS protocol ensures web server security. Let’s Encrypt provides a free SSL certificate. Install the certbot package with:

sudo apt install python3-certbot-nginx

Then, initiate the certificate creation:

sudo certbot --nginx --agree-tos --redirect --hsts --staple-ocsp --email you@example.com -d www.example.com

Replace with your email and domain name. This command sets up HTTPS with the required security features.

Setting Up Automatic Certificate Renewal

Let’s Encrypt certificates last 90 days. Set up automatic renewals with the Certbot script. Test the process:

sudo certbot renew --dry-run

If successful, add the renewal command to crontab:

sudo crontab -e

Include this line to renew daily at midnight:

00 00 */1 * * /usr/sbin/certbot-auto renew

Nginx Server Logs

Monitor your server logs for a well-maintained web server. By default, logs reside in /var/log/nginx. List them with:

cd /var/log/nginx && ls -l

The most relevant log files are the access.log and error.log. To monitor logs in real-time, use the tail -f command followed by the path to the log:

tail -f /var/log/nginx/access.log

Update Nginx

Before updating your Nginx server, creating a backup of your current configurations is wise. To back up your main nginx.conf file, use the following command:

sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx-backup.conf

In cases where you have extensively customized your Nginx setup, you might want to back up your entire Nginx directory:

sudo cp -r /etc/nginx/ /etc/nginx-bkup

With your configurations safely backed up, you can now proceed to update Nginx:

sudo apt update
sudo apt upgrade

Regularly backing up your configurations is good practice, especially in complex setups.

Remove Nginx

If you no longer need Nginx on your server, you can remove it by following these steps. First, ensure that the Nginx service is stopped:

sudo systemctl disable nginx --now

Next, altogether remove the Nginx package:

sudo apt remove nginx

You may still find remnants of Nginx configurations in the /etc/nginx directory. To remove these, use the command:

sudo rm -R /etc/nginx/

Remember that this will remove all your custom configuration files, so ensure you have everything you need backed up before proceeding with this step.

Configure Log Rotation Parameters in Nginx

Nginx includes a daily log rotation feature by default. However, you can customize these settings based on your needs.

Access Configuration File for Log Rotation

To modify the log rotation settings, you need to access the configuration file. Here’s how you can open it using the nano text editor:

sudo nano /etc/nginx/logrotate.d/nginx

Once you open the file, you’ll see content resembling the following. Adjust the directives in this file to fit your log retention and rotation needs, mainly if you use monitoring tools like fail2ban.

Sample Log Rotation Configuration File

/var/log/nginx/*.log {
  daily
  missingok
  rotate 14
  compress
  delaycompress
  notifempty
  create 0640 www-data adm
  sharedscripts
  prerotate
  if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
  run-parts /etc/logrotate.d/httpd-prerotate; \
  fi \
  endscript
  postrotate
  invoke-rc.d nginx rotate >/dev/null 2>&1
  endscript
}

Understanding Primary Configuration Parameters

Within this configuration, system administrators typically focus on two main settings:

  1. Daily: This setting sets the log rotation frequency. While it defaults to ‘daily,’ you can change it to ‘weekly’ or ‘monthly.’ However, daily rotations typically simplify log management.
  2. Rotate 14: This number tells the system how many log files to keep. For example, a setting of ’14’ retains the 14 latest logs. If you want to store only a week of logs, adjust this number to ‘7’.

While Nginx lets you modify other settings, always make changes with care. Changing settings without understanding their impact can cause unexpected results. Ensure you modify these settings to suit your needs without causing unintended issues.

Remember, there’s no one-size-fits-all approach to log management. Always assess your specific environment and requirements before making changes.

Closing Thoughts

In this guide, we walked through setting up Nginx on Debian, covering installation, configuration, and basic optimization. By combining Nginx’s efficiency with Debian’s stability, you’ve created a solid foundation for your web server. Remember to keep your server updated and explore additional Nginx modules for enhanced functionality. If you run into any issues, the strong communities around Debian and Nginx are always great resources. Thanks for following along, and happy hosting!

Leave a Comment