update web servers dir name

This commit is contained in:
2025-09-28 15:38:58 +03:30
parent 12f7d67480
commit bef9b7b5b7
11 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,94 @@
# 🔐 Certbot SSL Certificate Management Guide
## 📦 Install Certbot
```bash
apt install certbot
```
Installs **Certbot**, the free tool to automatically obtain and manage SSL/TLS certificates from **Let's Encrypt**.
---
## 🖥️ Method 1 Standalone Mode
```bash
certbot certonly --standalone -d www.example.com
```
💡 **Standalone mode** runs its own temporary web server to complete the verification.
* Use when no web server (Apache/Nginx) is running on the same port.
* Certificates will be saved in:
* All versions: `/etc/letsencrypt/archive/`
* Latest version (symlink): `/etc/letsencrypt/live/`
---
## 🌐 Method 2 Webroot Mode
```bash
certbot certonly --webroot --webroot-path <path> -d <domain>
```
📌 **Webroot mode** places a verification file in your website's public directory.
* `<path>` = your website's document root (e.g., `/var/www/html`)
* Use when your site is already running and accessible.
---
## 🛠️ Method 3 Manual DNS Challenge
```bash
certbot certonly --manual --preferred-challenges dns -d <domain>
```
🔹 **DNS mode** requires you to manually add a TXT record to your domains DNS.
* Best for **wildcard** certificates (`*.example.com`)
* Works even without a running web server.
---
## ♻️ Renew Certificates
### Automatic Renewal
```bash
certbot renew
```
* Renews all certificates close to expiration.
### Force Renewal
```bash
certbot renew --force-renewal
```
* Renews certificates **immediately**, even if not expiring soon.
---
## 📅 Tips
* Certificates expire every **90 days** — always set up **auto-renew**.
* Test renewal without changes:
```bash
certbot renew --dry-run
```
* Restart your web server after renewal to apply new certificates:
```bash
systemctl restart nginx
# or
systemctl restart apache2
```
---
**With Certbot, your HTTPS setup can be fast, free, and automatic!** 🔒🚀

View File

@@ -0,0 +1,169 @@
# Setting up Nextcloud with Nginx
## Step 1: Update Repositories and Packages
```bash
apt update && apt upgrade -y
```
## Step 2: Install Nginx and MariaDB Server
```bash
apt install nginx mariadb-server
```
## Step 3: Install and Enable Dependencies and Certbot
```bash
apt install imagemagick php-imagick php-common php-mysql php-fpm php-gd php-json php-curl php-zip php-xml php-mbstring php-bz2 php-intl php-bcmath php-gmp php-zip libmagickcore-6.q16-6-extra
apt install certbot python3-certbot-nginx
systemctl start php8.1-fpm && systemctl enable php8.1-fpm
```
## Step 4: Get and Install Nextcloud
```bash
wget https://download.nextcloud.com/server/releases/nextcloud-28.0.4.zip && mkdir -p /sites/nextcloud && unzip nextcloud-*.zip -d /sites/nextcloud
```
## Step 5: Configure SQL
```bash
mysql -u root -p
```
```sql
CREATE DATABASE nextcloud_db;
CREATE USER 'admin2'@'localhost' IDENTIFIED BY '123';
GRANT ALL PRIVILEGES ON nextcloud_db.* TO 'admin2'@'localhost' IDENTIFIED BY '123';
FLUSH PRIVILEGES;
EXIT;
```
## Step 6: Configure Nginx
```bash
vim /etc/nginx/sites-enabled/default
```
**Nginx Configuration**
```conf
upstream php-handler {
server unix:/var/run/php/php8.1-fpm.sock;
}
server {
listen 80;
server_name _;
add_header Referrer-Policy "no-referrer" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Download-Options "noopen" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Permitted-Cross-Domain-Policies "none" always;
add_header X-Robots-Tag "none" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Strict-Transport-Security 'max-age=31536000; includeSubDomains; preload';
# Remove X-Powered-By, which is an information leak
fastcgi_hide_header X-Powered-By;
# Path to the root of your installation
root /sites/nextcloud/;
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
location = /.well-known/carddav {
return 301 $scheme://$host:$server_port/remote.php/dav;
}
location = /.well-known/caldav {
return 301 $scheme://$host:$server_port/remote.php/dav;
}
# set max upload size
client_max_body_size 512M;
fastcgi_buffers 64 4K;
# Enable gzip but do not remove ETag headers
gzip on;
gzip_vary on;
gzip_comp_level 4;
gzip_min_length 256;
gzip_proxied expired no-cache no-store private no_last_modified no_etag auth;
gzip_types application/atom+xml application/javascript application/json application/ld+json application/manifest+json application/rss+xml application/vnd.geo+json application/vnd.ms-fontobject application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/bmp image/svg+xml image/x-icon text/cache-manifest text/css text/plain text/vcard text/vnd.rim.location.xloc text/vtt text/x-component text/x-cross-domain-policy;
# Uncomment if your server is built with the ngx_pagespeed module
# This module is currently not supported.
# pagespeed off;
location / {
rewrite ^ /index.php;
}
location ~ ^\/(?:build|tests|config|lib|3rdparty|templates|data)\/ {
deny all;
}
location ~ ^\/(?:\.|autotest|occ|issue|indie|db_|console) {
deny all;
}
location ~ ^\/(?:index|remote|public|cron|core\/ajax\/update|status|ocs\/v[12]|updater\/.+|oc[ms]-provider\/.+)\.php(?:$|\/) {
fastcgi_split_path_info ^(.+?\.php)(\/.*|)$;
set $path_info $fastcgi_path_info;
try_files $fastcgi_script_name =404;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $path_info;
fastcgi_param HTTP on;
# Avoid sending the security headers twice
fastcgi_param modHeadersAvailable true;
# Enable pretty urls
fastcgi_param front_controller_active true;
fastcgi_pass php-handler;
fastcgi_intercept_errors on;
fastcgi_request_buffering off;
}
location ~ ^\/(?:updater|oc[ms]-provider)(?:$|\/) {
try_files $uri/ =404;
index index.php;
}
# Adding the cache control header for js, css and map files
# Make sure it is BELOW the PHP block
location ~ \.(?:css|js|woff2?|svg|gif|map)$ {
try_files $uri /index.php$request_uri;
add_header Cache-Control "public, max-age=15778463";
add_header Referrer-Policy "no-referrer" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Download-Options "noopen" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add
_header X-Permitted-Cross-Domain-Policies "none" always;
add_header X-Robots-Tag "none" always;
add_header X-XSS-Protection "1; mode=block" always;
# Optional: Don't log access to assets
access_log off;
}
location ~ \.(?:png|html|ttf|ico|jpg|jpeg|bcmap)$ {
try_files $uri /index.php$request_uri;
# Optional: Don't log access to other assets
access_log off;
}
}
```
## Step 7: Nginx Check
```bash
nginx -t # Check if configuration has errors
nginx -s reload
```

View File

@@ -0,0 +1,63 @@
# Nginx Documentation
## What Is Nginx?
**Nginx** (pronounced "engine-x") is a popular open-source web server and reverse proxy software. Known for its high performance, stability, rich feature set, simple configuration, and low resource consumption, Nginx has become one of the most widely used server applications worldwide.
Originally developed by Igor Sysoev, Nginx was designed to address the **C10k problem**—the challenge of handling 10,000 concurrent client connections. Nginx overcomes this limitation through an **event-driven, asynchronous architecture** that enables it to manage a vast number of simultaneous connections efficiently and with minimal resource usage.
---
## Key Features of Nginx
1. **High Performance**: Nginx is optimized to handle high-traffic websites and can serve static content faster than many other web servers.
2. **Stability**: Its design enables stable operation under heavy load, making it reliable for production environments.
3. **Low Resource Consumption**: The asynchronous architecture minimizes memory and CPU usage, making it suitable for high-concurrency environments.
4. **Flexibility**: Nginx can be easily configured to function as a web server, reverse proxy, load balancer, and more.
5. **Security**: Nginx supports SSL/TLS and can be configured for secure HTTPS connections, with built-in features to prevent DoS and DDoS attacks.
6. **Extensibility**: Through a range of modules, Nginx can be extended to support various functions such as caching, load balancing, access control, and more.
---
## Common Uses of Nginx
Nginxs versatility makes it a powerful tool for a wide range of applications. Below are some of its most common uses:
### 1. Web Server
Nginx can serve as a **standalone web server** to deliver static content like HTML files, images, videos, and more. Due to its efficiency, its commonly used to serve content directly or in front of other server applications for added performance and caching benefits.
### 2. Reverse Proxy
Acting as a **reverse proxy**, Nginx can forward client requests to another server, often used to route traffic to applications hosted on multiple servers. This approach helps manage and distribute incoming traffic, improving performance and security by hiding the backend server details from clients.
### 3. Load Balancer
Nginxs **load balancing** capabilities help distribute traffic across multiple servers. Load balancing not only increases fault tolerance by rerouting traffic in case of server failure but also enhances performance by preventing any single server from becoming overloaded.
Common load balancing methods in Nginx:
- **Round Robin**: Distributes requests sequentially across servers.
- **Least Connections**: Routes traffic to the server with the fewest active connections.
- **IP Hash**: Ensures clients are consistently routed to the same server based on their IP address.
### 4. Caching
Nginx can act as a **caching server** to store copies of frequently requested content. By serving cached content, Nginx can significantly reduce load times for users and lessen the workload on backend servers. This is especially beneficial for high-traffic websites with dynamic content.
---
## Additional Nginx Features
- **SSL/TLS Termination**: Nginx can terminate SSL/TLS connections, handling the encryption and decryption process to reduce the burden on backend servers.
- **URL Rewriting and Redirection**: With URL rewriting rules, Nginx can redirect requests to different URLs, enabling efficient handling of routing and user-friendly URLs.
- **Access Control**: Provides robust tools for managing access controls, including IP-based access restrictions, user authentication, and authorization.
- **HTTP/2 and HTTP/3 Support**: Supports newer HTTP protocols for faster and more secure connections.
- **Customizable Modules**: Nginxs modular architecture allows for custom modules, enabling functionality for a wide range of applications and configurations.
---

View File

@@ -0,0 +1,114 @@
# Installing Nginx
## Prerequisites
Before installing Nginx, ensure that you have root or sudo privileges on your system to carry out installation and configuration commands.
## Step-by-Step Installation
### For Debian-Based Systems (e.g., Ubuntu)
1. **Update Package Repositories**
Its a good practice to update your package repositories before installing new software to ensure youre downloading the latest version available.
```bash
sudo apt update
```
2. **Install Nginx**
Install Nginx from the package repository.
```bash
sudo apt install nginx
```
3. **Start Nginx Service**
Once installed, start the Nginx service.
```bash
sudo systemctl start nginx
```
4. **Enable Nginx to Start on Boot**
This command configures Nginx to start automatically whenever the server reboots.
```bash
sudo systemctl enable nginx
```
5. **Check Status (Optional)**
Verify that Nginx is running correctly.
```bash
sudo systemctl status nginx
```
### For Red Hat-Based Systems (e.g., CentOS, Fedora)
1. **Update Package Repositories**
As with Debian-based systems, its recommended to update repositories first.
```bash
sudo yum update
```
2. **Install Nginx**
On Red Hat-based systems, install Nginx with `yum`.
```bash
sudo yum install nginx
```
3. **Start Nginx Service**
Start Nginx after installation.
```bash
sudo systemctl start nginx
```
4. **Enable Nginx to Start on Boot**
Configure Nginx to launch automatically on system startup.
```bash
sudo systemctl enable nginx
```
5. **Check Status (Optional)**
Confirm that Nginx is running and functioning properly.
```bash
sudo systemctl status nginx
```
---
## Post-Installation Steps
1. **Allow Nginx Through the Firewall**
If your server has a firewall enabled, you may need to allow HTTP (port 80) and HTTPS (port 443) traffic.
### Debian-Based Systems:
```bash
sudo ufw allow 'Nginx Full'
```
### Red Hat-Based Systems:
```bash
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
```
2. **Verify Installation**
Open a web browser and navigate to your servers IP address or domain name:
```
http://<your-server-ip>
```
You should see the default Nginx welcome page, which confirms that the installation is successful.
---
## Troubleshooting Common Installation Issues
- **Error: Package Not Found**
If you encounter an error stating that the Nginx package was not found, you may need to install the **EPEL repository** (Extra Packages for Enterprise Linux) on Red Hat-based systems:
```bash
sudo yum install epel-release
sudo yum install nginx
```
- **Permission Denied Errors**
Ensure youre using `sudo` to run commands that require root privileges.
- **Firewall Blocking Access**
If you cant access Nginx via a browser, ensure that firewall rules are configured to allow HTTP/HTTPS traffic.

View File

@@ -0,0 +1,155 @@
# Setting Up a Web Server on Nginx
This guide covers the steps to configure Nginx as a basic web server to serve static HTML files and handle HTTP requests. We'll set up a sample web server on a Debian-based system, but the steps are similar for other Linux distributions.
---
## Prerequisites
- A server with **Nginx installed**. If you havent installed Nginx yet, follow the installation instructions in the [Nginx Installation Guide](2-Installtion.md) (or use the provided installation commands).
- **Root or sudo privileges** to edit configuration files and restart Nginx services.
---
## Step 1: Set Up the Web Directory
1. **Create a Directory for Your Website**
Nginx typically serves content from `/var/www/`. Create a new directory for your website content.
```bash
sudo mkdir -p /var/www/example.com/html
```
2. **Set Permissions**
Ensure that the Nginx user (usually `www-data`) has permission to read files in this directory.
```bash
sudo chown -R $USER:$USER /var/www/example.com/html
sudo chmod -R 755 /var/www/example.com
```
3. **Add a Sample HTML File**
Create a simple HTML file to confirm the setup.
```bash
echo "<html>
<head>
<title>Welcome to Example.com!</title>
</head>
<body>
<h1>Success! Nginx is serving your website.</h1>
</body>
</html>" | sudo tee /var/www/example.com/html/index.html
```
---
## Step 2: Configure Nginx to Serve the Website
1. **Create a Server Block Configuration File**
Nginx server blocks (similar to Apache virtual hosts) allow you to host multiple sites on the same server. Create a new configuration file for your site.
```bash
sudo vim /etc/nginx/sites-available/example.com
```
2. **Add Server Block Configuration**
Paste the following configuration into the file, replacing `example.com` with your domain or IP address:
```nginx
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;
}
}
```
3. **Enable the Server Block**
Link the configuration file to `sites-enabled` to enable it in Nginx:
```bash
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
```
4. **Test the Nginx Configuration**
Run the following command to check for any syntax errors in the configuration:
```bash
sudo nginx -t
```
5. **Reload Nginx to Apply Changes**
If the syntax test passes, reload Nginx to apply the new configuration.
```bash
sudo systemctl reload nginx
```
---
## Step 3: Configure DNS (Optional)
If you have a domain name, point it to your servers IP address in your DNS providers settings. Create an A record for `example.com` and, if desired, `www.example.com` to direct traffic to your servers IP address.
---
## Step 4: Access Your Website
In a web browser, navigate to `http://example.com` (replace `example.com` with your domain or IP address). You should see the sample HTML page you created, confirming that Nginx is serving your web content.
---
## Optional: Enabling HTTPS with SSL/TLS
For added security, you can configure HTTPS on your Nginx web server. One free and easy way to do this is by using **Lets Encrypt**.
1. **Install Certbot and the Nginx Plugin**
```bash
sudo apt install certbot python3-certbot-nginx
```
2. **Obtain and Install a Certificate**
Run the following Certbot command to automatically obtain and configure an SSL certificate for your website:
```bash
sudo certbot --nginx -d example.com -d www.example.com
```
3. **Verify Renewal Process**
Certificates from Lets Encrypt expire every 90 days. To automatically renew the certificates, add a cron job or use Certbots built-in renewal service:
```bash
sudo certbot renew --dry-run
```
Now your website will be accessible securely at `https://example.com`.
---
## Nginx Configuration Summary
Here's a quick reference for the key commands and file paths:
- **Site root directory**: `/var/www/example.com/html`
- **Nginx configuration files**:
- Site-specific: `/etc/nginx/sites-available/example.com`
- Enabled sites: `/etc/nginx/sites-enabled/`
- **Commands**:
- Check configuration syntax: `sudo nginx -t`
- Reload Nginx: `sudo systemctl reload nginx`
---
## Troubleshooting Common Issues
1. **Error: 403 Forbidden**
- Check that Nginx has the necessary permissions to access files in the root directory (`/var/www/example.com/html`). Use `chmod 755` and `chown` commands as shown above.
2. **Error: 404 Not Found**
- Ensure the `index.html` file exists in the specified directory and that `try_files` directive is correctly pointing to it.
3. **Configuration Errors**
- Always run `sudo nginx -t` to check configuration changes before reloading Nginx.
4. **SSL Issues**
- If HTTPS fails, make sure Certbot successfully installed the certificate and that the DNS settings correctly point to your servers IP address.
---

View File

@@ -0,0 +1,108 @@
# Setting Up a Reverse Proxy with Nginx
A reverse proxy can forward client requests to multiple backend servers, helping manage traffic, load balance, and secure the backend infrastructure. This guide provides a step-by-step approach to setting up a basic reverse proxy configuration in Nginx.
---
## Prerequisites
- **Nginx Installed**: Ensure that Nginx is installed and running on your server.
- **Root or sudo privileges** to edit configuration files and restart Nginx.
- **Backend Servers**: At least two backend services or applications you want to proxy, such as `http://web1.com` and `http://web2.com`.
---
## Step 1: Create the Reverse Proxy Configuration File
1. **Open a new configuration file** for your reverse proxy in Nginx's `sites-available` directory:
```bash
sudo vim /etc/nginx/sites-available/reverse-proxy.conf
```
2. **Define the Reverse Proxy Configuration**
Copy the following configuration into the file. Adjust the backend server names (`web1.com` and `web2.com`) to match your actual server addresses.
```nginx
server {
listen 80;
server_name _; # Use "_" to accept any hostname, or specify a domain name
# Proxy for the first backend application
location /web1 {
proxy_pass http://web1.com;
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 for the second backend application
location /web2 {
proxy_pass http://web2.com;
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;
}
# Log settings
access_log /var/log/nginx/reverse-proxy-access.log;
error_log /var/log/nginx/reverse-proxy-error.log;
}
```
### Explanation of Key Directives
- **listen**: Specifies the port Nginx will listen on (80 for HTTP).
- **server_name**: The domain name or IP address for this reverse proxy. Using `_` allows it to accept any hostname.
- **location**: Defines the URL path (`/web1`, `/web2`) to route to different backend servers.
- **proxy_pass**: Specifies the backend server URL to which traffic should be forwarded.
- **proxy_set_header**: Sets headers that pass client information to the backend, preserving the original IP and protocol.
- **access_log**: Logs access requests.
- **error_log**: Logs error messages for easier troubleshooting.
---
## Step 2: Enable the Reverse Proxy Configuration
1. **Create a symbolic link** from `sites-available` to `sites-enabled` to enable the reverse proxy configuration in Nginx:
```bash
sudo ln -s /etc/nginx/sites-available/reverse-proxy.conf /etc/nginx/sites-enabled/reverse-proxy.conf
```
2. **Verify Nginx Configuration**
Run a configuration test to ensure there are no syntax errors:
```bash
sudo nginx -t
```
3. **Reload Nginx** to apply the changes:
```bash
nginx -s reload
```
---
## Step 3: Access Your Reverse Proxy
With the reverse proxy set up, you can now access your backend services using the following URLs:
- **http://your-server-ip/web1**: For requests proxied to `http://web1.com`
- **http://your-server-ip/web2**: For requests proxied to `http://web2.com`
Replace `your-server-ip` with the actual IP address or domain name of your Nginx server.
---
## Troubleshooting Common Issues
- **Error: 502 Bad Gateway**
- This error usually occurs if the backend server is down or unreachable. Verify that the backend server addresses (`http://web1.com`, `http://web2.com`) are correct and accessible.
- **Permission Denied for Log Files**
- Make sure the log file paths are writable by Nginx. Use `sudo chown www-data:www-data /var/log/nginx/reverse-proxy-access.log` if necessary.
- **Configuration Errors**
- Always test configuration changes using `sudo nginx -t` before reloading or restarting Nginx.
---

View File

@@ -0,0 +1,128 @@
# Setting Up Load Balancing with Nginx
Load balancing with Nginx helps distribute incoming traffic across multiple backend servers, improving the performance, reliability, and availability of your applications. This guide provides a step-by-step process to configure a basic round-robin load balancer using Nginx.
---
## Prerequisites
- **Nginx Installed**: Ensure Nginx is installed on your server.
- **Root or sudo privileges** to edit configuration files and restart Nginx.
- **Multiple Backend Servers**: Two or more backend servers with applications running. In this example, we use `10.10.10.1` and `10.10.10.2`.
---
## Step 1: Create the Load Balancer Configuration File
1. **Open a new configuration file** for the load balancer in Nginxs `sites-available` directory:
```bash
sudo vim /etc/nginx/sites-available/load_balancer.conf
```
2. **Define the Load Balancer Configuration**
Copy the following configuration into the file. Replace the IP addresses (`10.10.10.1` and `10.10.10.2`) with the actual IP addresses of your backend servers.
```nginx
# Define the upstream group of backend servers
upstream backend_servers {
server 10.10.10.1;
server 10.10.10.2;
}
server {
listen 80;
server_name _; # Accept any hostname or specify a domain name if needed
location / {
proxy_pass http://backend_servers; # Forward requests to the backend servers group
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;
}
# Log files
access_log /var/log/nginx/load_balancer_access.log;
error_log /var/log/nginx/load_balancer_error.log;
}
```
### Explanation of Key Directives
- **upstream**: Defines a pool of backend servers to which Nginx will forward traffic. By default, Nginx uses a round-robin algorithm, sending requests to each server in turn.
- **server_name**: Accepts any hostname (`_`) or a specific domain name.
- **proxy_pass**: Specifies the backend server group defined by `upstream`.
- **proxy_set_header**: Passes client information such as the original IP and protocol to the backend servers.
- **access_log** and **error_log**: Directs logs to specified files for easier monitoring and troubleshooting.
---
## Step 2: Enable the Load Balancer Configuration
1. **Create a symbolic link** to `sites-enabled` to activate the load balancer configuration in Nginx:
```bash
sudo ln -s /etc/nginx/sites-available/load_balancer.conf /etc/nginx/sites-enabled/load_balancer.conf
```
2. **Verify Nginx Configuration**
Test the Nginx configuration for syntax errors:
```bash
sudo nginx -t
```
3. **Reload Nginx** to apply the new configuration:
```bash
sudo nginx -s reload
```
---
## Step 3: Test the Load Balancer
To ensure the load balancer is distributing traffic correctly, you can access the Nginx servers IP address or domain name in your web browser:
```
http://your-server-ip/
```
You should see responses from the backend servers. Testing multiple times should show responses alternating between `10.10.10.1` and `10.10.10.2`, as Nginx forwards requests in a round-robin fashion.
---
## Optional: Configure Additional Load Balancing Methods
Nginx supports multiple load balancing algorithms, which you can specify within the `upstream` block:
- **Round Robin (default)**: Distributes requests evenly across all servers.
- **Least Connections**: Directs traffic to the server with the fewest active connections.
```nginx
upstream backend_servers {
least_conn;
server 10.10.10.1;
server 10.10.10.2;
}
```
- **IP Hash**: Directs requests from the same client IP to the same backend server, which can help with session persistence.
```nginx
upstream backend_servers {
ip_hash;
server 10.10.10.1;
server 10.10.10.2;
}
```
---
## Troubleshooting Common Issues
- **Error: 502 Bad Gateway**
- This error often means that the backend server is unreachable or down. Verify the IP addresses and ensure each backend server is running and accessible.
- **Permission Denied for Log Files**
- Ensure the log file paths are writable by Nginx. Adjust permissions as needed:
```bash
sudo chown www-data:www-data /var/log/nginx/load_balancer_access.log
```
- **Configuration Errors**
- Always test configuration changes with `sudo nginx -t` before reloading or restarting Nginx.

View File

@@ -0,0 +1,54 @@
### 📄 **NGINX File Server Configuration**
This configuration sets up an NGINX server to serve files from two different directories:
* `/srv/files` for general file browsing at the root path (`/`)
* `/srv/images` for image browsing at `/image`
```nginx
server {
# Define the domain name for this server block
server_name domain;
# Default root directory for the server
root /srv/files;
# Serve files and list directory contents at the root URL (e.g., http://domain/)
location / {
autoindex on; # Enables directory listing
}
# Serve images and list contents at /image (e.g., http://domain/image/)
location /image {
autoindex on; # Enables directory listing
root /srv/images; # Note: this overrides the global root
# Final path served will be /srv/images/image/ due to how root works
}
}
```
---
### ⚠️ **Important Notes**
1. **Path Behavior**:
* In the `/image` block, using `root` adds the location path (`/image`) to the end. So `http://domain/image/` will map to `/srv/images/image/`.
* If you want `/image/` to map directly to `/srv/images/`, use `alias` instead:
```nginx
location /image/ {
autoindex on;
alias /srv/images/;
}
```
2. **Security**:
* Be cautious when enabling `autoindex`; it exposes directory contents to the public.
* Consider restricting access or adding authentication for sensitive directories.
3. **Permissions**:
* Ensure the NGINX user (usually `www-data`) has read access to the directories.

View File

@@ -0,0 +1,56 @@
# 🔐 Nginx SSL Configuration Guide
## 📄 Example Server Block (HTTPS)
```nginx
listen 443 ssl;
server_name example.com www.example.com;
# 🔒 SSL Certificate (Generated by Certbot)
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# 📂 Website Root
root /var/www/example.com/html;
index index.html;
# 🚦 Request Handling
location / {
try_files $uri $uri/ =404;
}
```
---
## 🗂️ What Each Part Does
| Directive | Meaning |
| ---------------------------- | ------------------------------------------------------ |
| `listen 443 ssl;` | Listens on port **443** for secure HTTPS traffic. |
| `server_name` | Specifies the domain(s) for this site. |
| `ssl_certificate` | The **full certificate chain** file from Certbot. |
| `ssl_certificate_key` | The **private key** file from Certbot. |
| `root` | Directory containing your websites files. |
| `index` | Default file served for a directory request. |
| `try_files $uri $uri/ =404;` | Checks if a file/directory exists, else returns a 404. |
---
## ⚠️ SSL Notes
* Certbot certificates are stored here:
```
/etc/letsencrypt/live/<your-domain>/
```
* Certificates **expire every 90 days** — set up auto-renew:
```bash
certbot renew --quiet
```
* After renewal, always reload Nginx to apply changes:
```bash
systemctl reload nginx
```

View File

@@ -0,0 +1,75 @@
# 🔐🔑 Nginx SSL with HTTP Basic Authentication
## 📄 Example Secure Server Block (HTTPS + Password Protection)
```nginx
listen 443 ssl;
server_name example.com www.example.com;
# 🔒 SSL Certificates (Generated by Certbot)
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# 📂 Website Root
root /var/www/example.com/html;
index index.html;
# 🔑 Password-Protected Location
location / {
auth_basic "Admin";
auth_basic_user_file /etc/nginx/.htpasswd;
try_files $uri $uri/ =404;
}
```
---
## 🗂️ Explanation of Key Parts
| Directive | Purpose |
| ---------------------- | ------------------------------------------------------------------- |
| `auth_basic "Admin";` | Enables **HTTP Basic Authentication** with prompt title “Admin”. |
| `auth_basic_user_file` | Points to the `.htpasswd` file containing username/password hashes. |
| `.htpasswd` file | Stores encrypted credentials — created using `htpasswd` command. |
| SSL lines | Load the certificate and private key from **Certbot**. |
---
## 🛠️ How to Set Up Password Protection
### 1⃣ Install `apache2-utils` (for `htpasswd` tool)
```bash
apt install apache2-utils
```
### 2⃣ Create the `.htpasswd` File
```bash
htpasswd -c /etc/nginx/.htpasswd <username>
```
* `-c` creates a **new file** (omit `-c` if adding more users).
* Youll be prompted to set a password.
### 3⃣ Adjust File Permissions
```bash
chmod 640 /etc/nginx/.htpasswd
chown root:www-data /etc/nginx/.htpasswd
```
### 4⃣ Test and Reload Nginx
```bash
nginx -t
systemctl reload nginx
```
---
## ⚠️ Security Notes
* Always store `.htpasswd` **outside** your web root.
* Passwords in `.htpasswd` are hashed, but still protect the file with correct permissions.
* Works best for **admin panels**, **staging sites**, or private areas.

View File

@@ -0,0 +1,134 @@
# Nginx Rate Limiting Guide
Nginx can control request rates using the **Leaky Bucket algorithm**. This helps prevent abuse, protect resources, and manage traffic efficiently.
---
## Basic Configuration
```nginx
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=1r/s;
server {
server_name files.usethelinux.shop;
root /srv/files;
location / {
autoindex on;
limit_req zone=mylimit burst=4 nodelay;
}
}
```
### Explanation:
* `$binary_remote_addr` → Client IP Address
* `10m` → Zone memory size (10MB) can handle approximately 160,000 addresses
* `1r/s` → 1 request per second
* `burst=4` → Allows a peak of 4 requests without delay
* `nodelay` → Rejects requests immediately when the limit is exceeded
> The rate can also be set lower, e.g., `10r/min` (10 requests per minute)
---
## Two-Stage Configuration (Smooth Bursting)
```nginx
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=5r/s;
server {
server_name files.usethelinux.shop;
root /srv/files;
location / {
autoindex on;
limit_req zone=mylimit burst=4 delay=2;
}
}
```
### Behavior:
* Requests 17 → Handled at full speed
* Requests 89 → Handled with delay
* Requests above 9 → Rejected
---
## Advanced Configuration
```nginx
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=3r/s;
server {
server_name files.usethelinux.shop;
root /srv/files;
location / {
autoindex on;
limit_req zone=mylimit burst=4 delay=2;
limit_req_status 403;
limit_req_log_level warn;
}
error_log /var/log/nginx/rate-error.log warn;
}
```
### Additional Options:
* `limit_req_status` → Status code returned when requests are rejected (e.g., 403)
* `limit_req_log_level` → Logging level for rate-limit warnings (requires `error_log` configured)
---
## Whitelist Specific IPs
```nginx
geo $limit {
default 1;
10.0.0.0/8 0;
192.168.0.0/24 0;
93.127.222.112/32 0;
}
map $limit $limit_key {
0 "";
1 $binary_remote_addr;
}
limit_req_zone $limit_key zone=mylimit:10m rate=2r/s;
server {
server_name files.usethelinux.shop;
root /srv/files;
location / {
autoindex on;
limit_req zone=mylimit burst=3 delay=1;
limit_req_status 403;
limit_req_log_level warn;
}
error_log /var/log/nginx/rate-error.log warn;
}
```
### Explanation:
* `geo` → Defines a variable with default `1` (all clients)
* `map` → Applies `limit_req_zone` only to non-whitelisted IPs
* Whitelisted IPs (value `0`) are not limited, others follow rate limits
---
## Summary
* **`limit_req_zone`** → Defines the rate-limiting key and storage
* **`limit_req`** → Applies the rate limit to a location
* **Burst & Delay** → Control traffic spikes smoothly
* **Whitelist** → Exclude trusted IPs from rate limiting
* **Logging & Status** → Monitor and handle rejected requests efficiently