Nginx is a highly efficient and scalable web server, widely recognized for its ability to handle a large number of concurrent connections with low resource consumption. It is ideal for serving static content quickly, acting as a reverse proxy, and balancing load across multiple servers. With its modular architecture, Nginx can be easily configured to meet a wide range of web server needs, including SSL/TLS support, caching, and URL rewriting, making it a versatile solution for both small-scale deployments and high-traffic environments.
On Fedora 40 or 39, you can install Nginx using Fedora’s built-in package management tools, which ensure you have a secure and up-to-date version of the software. This guide will take you through the installation process, ensuring that Nginx is properly set up to handle your web server requirements. Whether you’re hosting a simple site or managing complex web services, Nginx on Fedora provides the reliability and performance you need.
Update Fedora Before Nginx Installation
To begin, it’s crucial to update your Fedora system. This step ensures that all your system’s packages are current, paving the way for a smooth NGINX installation.
Execute the command below:
sudo dnf upgrade --refresh
Install Nginx via DNF Command
Fedora includes NGINX in its default repository, typically offering the latest or very recent version. This availability simplifies installation and future maintenance, especially outside strict production environments where the newest features of NGINX are desired.
Install NGINX on your Fedora system with this command:
sudo dnf install nginx
Confirm Nginx Installation
Once NGINX is installed, it’s good practice to confirm the installation. This verification helps ensure that NGINX is correctly set up and operational on your system.
Check the installed version of NGINX by running:
nginx -v
The output should display the installed NGINX version, confirming a successful installation.
Configure Firewall Rules for NGINX
Adjusting Firewall Settings for HTTP and HTTPS
NGINX requires specific ports to be open to handle web traffic. By default, Fedora’s firewall does not automatically configure these rules. For NGINX to serve web content, you must manually add rules for HTTP (port 80) and HTTPS (port 443). Use the following commands to adjust your firewall settings:
Open HTTP port 80:
sudo firewall-cmd --permanent --zone=public --add-service=http
For HTTPS port 443:
sudo firewall-cmd --permanent --zone=public --add-service=https
Applying Firewall Changes
After adding the necessary services, apply the new firewall rules by reloading firewalld:
sudo firewall-cmd --reload
This action activates the new settings, ensuring your Fedora system is prepared to route HTTP and HTTPS traffic to NGINX.
Verifying NGINX Service Status
Checking NGINX Service Health
After installing NGINX, confirming the service is operational is crucial. This verification step ensures that NGINX is running correctly on your Fedora system. Use the following command to check the status of the NGINX service:
systemctl status nginx
This command queries the system’s service manager to provide a status report on NGINX, indicating whether the service is active and running without issues.
Enabling and Starting NGINX Service
If NGINX is inactive, you need to start the service and enable it to launch at boot. Execute the following command to both start NGINX now and set it to start on the system boot automatically:
sudo systemctl enable nginx --now
This command adjusts the system’s service configurations, ensuring NGINX is running and set to persist across reboots.
Testing NGINX Configuration
To confirm that NGINX is correctly configured and responsive, access the default NGINX landing page. First, ascertain your server’s IP address with this command:
curl -4 icanhazip.com
Should the curl command be unavailable, install it using:
sudo dnf install curl
Upon successful execution, you will receive an output displaying the server’s IP address, formatted as XXX.XXX.XXX.XXX.
Accessing the Default NGINX Page
With the server’s IP address, you can now navigate to NGINX’s default landing page. Open your web browser and enter the following URL, replacing your_server_ip with the actual IP address:
http://your_server_ip
Alternatively, if you are performing this check on the local machine where NGINX is installed, you can use:
http://localhost
You should be greeted with the default NGINX welcome page, confirming that the web server is correctly installed and serving pages.
By accessing the NGINX test page, you validate NGINX’s successful setup and readiness for further configuration and deployment of web applications.
Configure Domain Directory Structure for NGINX
To initiate the setup for hosting a domain, such as “example.com,” begin by constructing the required directory structure within /var/www/. Throughout this process, replace “your_domain” with your actual domain name.
Create Domain Directory
Generate the domain’s root directory to house the website’s files. The -p parameter ensures that any necessary parent directories are also created:
sudo mkdir -p /var/www/your_domain/html
Set Directory Ownership
After establishing the directory, it’s crucial to set the proper ownership. This action assigns your user account as the owner, permitting you to modify the website’s files:
sudo chown -R $USER:$USER /var/www/your_domain/html
Configure Directory Permissions
Next, modify the directory permissions to secure and define access levels. The following command sets full permissions for the owner and only read and execute permissions for others, which is standard practice for web content directories:
sudo chmod -R 755 /var/www/your_domain
While some configurations suggest using /usr/share/nginx/html, the /var/www directory is recommended for its simplicity and ease of use for those new to server management.
Create an HTML Test Page For the Nginx Test
Create the Test HTML Page
Initiate the creation of a test HTML page to confirm the operational status of your NGINX server. This page will validate the correct setup of your NGINX installation and server block directories.
Launch the nano text editor to begin crafting your test page:
nano /var/www/your_domain/html/index.html
Within the nano editor, populate your file with the following HTML structure, ensuring to replace your_domain with your actual domain name:
<!DOCTYPE html>
<html>
<head>
<title>Welcome to your_domain!</title>
</head>
<body>
<h1>Success! The your_domain server block is working!</h1>
</body>
</html>
Saving and Exiting the Editor
After inputting the HTML content, save your progress by pressing CTRL+O. Confirm the save operation and then exit the editor with CTRL+X.
Creating this test HTML page is a pivotal step in verifying the proper setup of your NGINX server, ensuring it’s configured and ready for serving content.
Create Nginx Server Block
Creating Directory Structure for Server Blocks
Begin by establishing the directory structure necessary for NGINX server blocks. Execute the commands below to create the sites-available and sites-enabled directories, which will house your server block configurations:
sudo mkdir /etc/nginx/sites-available
sudo mkdir /etc/nginx/sites-enabled
Configuring the NGINX Main Configuration File
Next, modify the main NGINX configuration file to include your server blocks. Open the nginx.conf file with the following command:
sudo nano /etc/nginx/nginx.conf
Within the file, comment out the line that includes the default server blocks and add a line to include server blocks from the sites-enabled directory:
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;
events {
worker_connections 1024;
}
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 4096;
include /etc/nginx/mime.types;
default_type application/octet-stream;
###EDIT HERE### #
# include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*.conf;
}
Save your changes with CTRL+O and exit with CTRL+X.
Crafting Your Domain’s Server Block File
Now, create a server block configuration file for your domain. Replace your_domain with your actual domain name:
sudo nano /etc/nginx/sites-available/your_domain.conf
Insert the following configuration, adjusting the server_name and root directives to match your domain and document root:
server {
listen 80;
listen [::]:80;
server_name your_domain www.your_domain;
root /var/www/your_domain/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
After customizing the configuration, save the file (CTRL+O) and exit (CTRL+X).
Enable Nginx Server Block
Enable your domain’s server block by creating a symbolic link to the sites-enabled directory:
sudo ln -s /etc/nginx/sites-available/your_domain.conf /etc/nginx/sites-enabled/
This step ensures NGINX includes your server block during the next reload.
Tweaking Hash Bucket Size in NGINX Configuration
Before finalizing, it’s crucial to adjust the server_names_hash_bucket_size to prevent potential configuration issues. Open the nginx.conf file again:
sudo nano /etc/nginx/nginx.conf
Ensure the following line is uncommented or added:
server_names_hash_bucket_size 64;
Testing NGINX Configuration
Validate your NGINX configuration to avoid runtime errors:
sudo nginx -t
Look for a success message indicating a valid configuration.
Restarting NGINX to Apply Changes
If the configuration test is successful, proceed to restart NGINX to apply your changes:
sudo systemctl restart nginx
Verifying Your Server Block
To confirm your server block is active, navigate to your domain in a web browser.
If the test page does not display as expected, check for any default server blocks in nginx.conf that may need removal.
Additional Commands For Nginx
Secure Nginx with Let’s Encrypt SSL Free Certificate
Install Certbot for NGINX
Boost the security of your NGINX server by enabling HTTPS with a free SSL certificate from Let’s Encrypt. Begin by installing the Certbot software, which will automate the certificate acquisition process:
sudo dnf install python3-certbot-nginx
Obtain and Install the SSL Certificate
With Certbot installed, you can now obtain your SSL certificate. Run the following command, replacing the email and domain with your information:
sudo certbot --nginx --agree-tos --redirect --hsts --staple-ocsp --email you@example.com -d www.example.com
This command obtains the certificate and modifies your NGINX configuration to enforce HTTPS by implementing 301 redirects, adding the Strict-Transport-Security header, and enabling OCSP Stapling, enhancing your server’s security posture.
Automating SSL Certificate Renewal
Certificates issued by Let’s Encrypt are valid for 90 days. To avoid manual renewals, automate the process with a cron job. First, test the renewal process:
sudo certbot renew --dry-run
If the dry run is successful, proceed to edit your crontab:
sudo crontab -e
If Cron is not installed on your Fedora system, install it with:
sudo dnf install cronie
In the crontab, schedule a daily check for certificate renewal:
00 00 */1 * * /usr/sbin/certbot-auto renew
Save your crontab with SHIFT + :, type wq to write and quit, and then press Enter
.
You should see a confirmation message indicating the successful scheduling of the task:
crontab: installing new crontab
Managing Nginx Service
With Nginx now successfully set up on your server, it is crucial to keep in mind the following management guidelines:
Stopping the NGINX Web Server
To halt the NGINX service, execute the following command:
sudo systemctl stop nginx
Starting the NGINX Web Server
Initiate the NGINX service with this command:
sudo systemctl start nginx
Restarting the NGINX Web Server
For a complete restart of the NGINX service, use:
sudo systemctl restart nginx
Reloading the NGINX Web Server
Apply minor changes without restarting by reloading NGINX:
sudo systemctl reload nginx
Disabling NGINX on Server Boot
Prevent NGINX from starting during system boot:
sudo systemctl disable nginx
Enabling NGINX on Server Boot
Set NGINX to start automatically on boot, although note that it defaults to enabled upon installation:
sudo systemctl enable nginx
These commands are integral for the routine management of the NGINX service, ensuring that administrators can effectively control the web server’s operation within their Fedora Linux environment.
Accessing NGINX Server Logs
Navigating to the Logs Directory
To begin, switch to the NGINX logs directory:
cd /var/log/nginx/
List the contents to view available log files:
ls
Within this directory, access.log and error.log are the primary files that store incoming server requests and error messages, respectively. Regularly inspecting these logs is crucial for identifying issues, optimizing performance, and maintaining server health.
Monitoring Logs in Real-Time
For live log monitoring, the “tail” command is invaluable:
sudo tail -f /var/log/nginx/access.log
This command continuously outputs new log entries upon their recording, serving as a handy tool for immediate troubleshooting.
Reviewing Recent Log Activity
To review the most recent entries, display the last 30 lines of the access log:
sudo tail -f /var/log/nginx/access.log -n 30
Advanced Log Filtering Techniques
For more advanced log analysis, grep can be used to filter logs. For instance, to find all entries related to a specific IP address, use:
grep 'IP_ADDRESS' /var/log/nginx/access.log
Replace IP_ADDRESS with the actual IP address you’re investigating.
To monitor error logs for specific dates, combine grep with a date string:
grep '2023-11-07' /var/log/nginx/error.log
This filters entries from November 7, 2023.
For a more sophisticated analysis, tools like awk can extract specific fields, such as response codes:
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -n
This sequence prints out the HTTP status codes from the access log, counts them, and sorts them to identify the most frequent codes.
Configuring NGINX Log Rotation
Customizing Log Rotation Settings
To tailor log rotation for NGINX, edit the configuration file in /etc/logrotate.d/:
sudo nano /etc/logrotate.d/nginx
This file specifies NGINX’s log archiving, compression, and rotation management. It defaults to sensible settings and allows customization to conform to particular logging policies or system requirements.
Understanding Logrotate Configuration Options
Here’s a breakdown of key directives in the logrotate configuration:
- Daily, Weekly, Monthly: Sets the log rotation interval. The default is daily, but it can be adjusted to weekly or monthly based on how frequently you want to archive logs.
- Rotate: Specifies the number of old log files to retain. The default is 14, meaning after 14 rotations, the oldest file is deleted.
- Compress: Enables compression of rotated log files to save space. By default, this is enabled.
- Delaycompress: Postpones compression to the next rotation cycle, usually paired with compress.
- Missingok: Allows logrotate to proceed without error if a log file is absent.
- Create: Sets permissions and ownership for new log files post-rotation, ensuring secure and proper access.
- Sharedscripts: Executes the postrotate script once after all logs rotate, which is efficient for reloading services.
Sample NGINX Logrotate Configuration
Below is a sample configuration with explanations for each directive:
/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
}
Best Practices and Considerations
- Default Settings: Unless there’s a compelling reason, using NGINX’s default settings is advisable.
- System Requirements: Adjust settings based on system usage, storage capacity, and specific application needs.
- Security Monitoring: If using tools like fail2ban, ensure log rotation settings do not interfere with log monitoring.
By understanding and configuring these settings, administrators can ensure efficient, secure management of NGINX logs in compliance with their logging policies.
Updating NGINX
Backing Up the NGINX Configuration
Before initiating an update, safeguard your NGINX configuration:
sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak
Executing this command duplicates the nginx.conf file, appending .bak to the filename. This backup serves as a safety net, allowing you to restore your original settings should the update process affect your custom configurations.
Archiving the Entire NGINX Directory
For a comprehensive backup, archive the entire NGINX directory:
sudo tar -czvf nginx_backup.tar.gz /etc/nginx/
This command compiles all configuration files, modules, and related data into a gzipped tar archive, ensuring you have a complete snapshot of your current NGINX setup.
Executing the NGINX Update
To update NGINX, refresh your Fedora repositories and apply the latest updates:
sudo dnf upgrade --refresh
This command checks for updates and, if available, prompts you to proceed with the upgrade process, ensuring NGINX runs the most recent version with all security patches and improvements.
Note: Always review the changes before applying updates, especially for a service as critical as NGINX, to avoid unexpected downtime or configuration issues.
Uninstalling NGINX
Remove NGINX
To remove NGINX from your system, execute the following command:
sudo dnf remove nginx
This command uninstalls NGINX and removes any orphaned dependencies accompanying its installation, which are now unnecessary.
Note: This action will stop all NGINX services and remove the associated files. If you plan to use them later or migrate to a different web server, ensure you have backed up any necessary configuration files or website data.
Conclusion
By installing Nginx on your Fedora system, you’ve established a reliable and efficient web server ready to handle a variety of tasks, from serving static files to managing traffic for more complex applications. Regular updates via Fedora’s package management tools will help keep your Nginx installation secure and running smoothly. Consider fine-tuning Nginx’s configuration to suit your specific needs, whether it’s optimizing performance, enhancing security, or setting up advanced features like load balancing. With proper management, Nginx will continue to deliver robust performance for your Fedora-based web services.