This guide will demonstrate how to install Nginx on Fedora Linux using the command-line terminal with DNF package manager, accompanied by first-time setup tips.
Nginx is a powerful, open-source software for web serving, reverse proxying, caching, load balancing, media streaming, and more. It’s known for its high performance, stability, scalability, and low resource consumption. Nginx excels in delivering static content quickly and is designed to pass dynamic requests off to other software that is better suited for those purposes. Its asynchronous event-driven architecture enables it to handle multiple connections simultaneously, making it an excellent choice for high-traffic websites.
Here are some key highlights of Nginx:
- High Performance: Optimized to handle thousands of simultaneous connections with a low memory footprint.
- Scalability: Easily scales on modern hardware, supporting the growth of your website’s traffic.
- Flexibility: Offers extensive configuration options to tailor its functionality to your specific needs.
- Security: Provides robust security features, including rate limiting and client request filtering.
- Efficiency: Consumes very little memory and CPU resources, enhancing overall system efficiency.
- Reverse Proxy Capabilities: Can be used as a reverse proxy, directing client requests to the appropriate backend server.
- Load Balancing: Distributes incoming network traffic across multiple servers, improving the responsiveness of your applications.
- Extensibility: Supports a wide range of modules that extend its core functionalities.
Now, let’s transition to the technical how-to, guiding you through the installation process of Nginx on Fedora Linux, ensuring you’re equipped to leverage its full potential.
Install Nginx on Fedora via DNF
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 a version that is either the latest or very recent. This availability simplifies the 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.
Note: By default, Fedora installs the stable version of Nginx. However, for those who require the mainline version of Nginx, a guide is available that explains the steps to enable Nginx Mainline on Fedora Linux.
Configure Firewall Rules for NGINX on Fedora
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 on Fedora
Checking NGINX Service Health
After installing NGINX, it’s crucial to confirm that the service is operational. 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 the successful setup and readiness of NGINX for further configuration and deployment of web applications.
Configure Domain Directory Structure for NGINX on Fedora
To initiate the setup for hosting a domain, such as “example.com,” begin by constructing the required directory structure within /var/www/
. Replace “your_domain” with your actual domain name throughout this process.
Create Domain Directory
Generate the domain’s root directory, which will 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, granting you the permission 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
, for those new to server management, the /var/www
directory is recommended for its simplicity and ease of use.
Create an HTML Test Page For Nginx Test on Fedora
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 on Fedora
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 on Fedora
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 on Fedora
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. Regular inspection of 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 and sorts them to identify the most frequent codes.
Configuring NGINX Log Rotation on Fedora
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 the management of log archiving, compression, and rotation by NGINX. It defaults to sensible settings, yet it 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. Default is daily, but 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, it’s advisable to stick with the default settings provided by NGINX.
- 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.
Administrators can ensure efficient, secure management of NGINX logs in compliance with their logging policies by understanding and configuring these settings.
Updating NGINX on Fedora
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 from Fedora
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: It’s important to consider that this action will stop all NGINX services and remove the associated files. Ensure that you have backed up any necessary configuration files or website data if you plan to use them later or migrate to a different web server.
Conclusion
To summarize, deploying NGINX on Fedora Linux involves a series of clear-cut steps that equip you with a fully operational web server in minimal time. It’s imperative to regularly back up your NGINX configuration files, particularly before updates or removals, to safeguard your custom settings. Proper configuration of server blocks, creation of a test HTML page, and securing connections with Let’s Encrypt SSL are critical for a seamless and secure web experience. Once NGINX is in place, you’re set to deliver dynamic content and manage multiple websites efficiently, leveraging NGINX’s flexibility and power.