Setting up a web server might sound complicated, but with this simple guide, you’ll learn how to install Nginx on CentOS 7 easily. Whether you’re running a personal website or a business project, Nginx is a great choice for serving your web pages quickly and reliably.
What is Nginx and Why Use CentOS 7?
What is Nginx?
Nginx is a popular web server that helps deliver websites to users quickly and efficiently. It’s known for handling many visitors at the same time without slowing down. Besides serving web pages, Nginx can also work as a reverse proxy, load balancer, and HTTP cache.
Why Choose CentOS 7?
CentOS 7 is a stable and secure operating system that’s free to use. It’s widely used for servers because it runs smoothly for long periods without needing frequent restarts. CentOS 7 works well with Nginx, making it a great choice for your web server.
Things You Need Before Starting
Before you begin installing Nginx, make sure you have everything you need.
System Requirements
Your server should meet these basic requirements:
- Operating System: CentOS 7 (64-bit)
- Memory (RAM): At least 1 GB (4 GB is better)
- Processor (CPU): 1 GHz or faster
- Disk Space: Minimum of 10 GB available
Access to Your Server
You need to have root or sudo access to your server. This means you can run commands that make changes to the system. If you’re using a cloud service like AWS or DigitalOcean, you should have these permissions by default.
Update Your System
Before installing anything, updating your system to the latest packages is a good idea.
- Open your terminal.
- Run the following command:
sudo yum update -y
This command updates all installed packages to their latest versions.
Step-by-Step Installation of Nginx
Now, let’s install Nginx on your CentOS 7 server.
Add the EPEL Repository
Nginx is available in the EPEL (Extra Packages for Enterprise Linux) repository. You must first add this repository to your system.
- Run this command to install EPEL:
sudo yum install epel-release -y
- Check that EPEL is enabled:
sudo yum repolist
You should see
epel
listed among the repositories.
Install Nginx
With EPEL enabled, you can now install Nginx.
- Run the installation command:
sudo yum install nginx -y
- Wait for the installation to complete. This command installs Nginx and any needed dependencies.
Start and Enable Nginx
After installing, start the Nginx service and make sure it starts automatically when the server boots.
- Start Nginx:
sudo systemctl start nginx
- Enable Nginx to start on boot:
sudo systemctl enable nginx
- Check that Nginx is running:
sudo systemctl status nginx
You should see that Nginx is active (running).
Setting Up Nginx
Configuring Nginx helps it serve your website correctly.
Where Are the Configuration Files?
Nginx’s main configuration file is located at /etc/nginx/nginx.conf
. This file controls global settings. For individual websites, you can add files in the /etc/nginx/conf.d/
directory.
Basic Settings
Let’s look at some key settings in the main configuration file.
- Open the configuration file with a text editor:
sudo vi /etc/nginx/nginx.conf
- Important parts to check:
- worker_processes: Sets how many processes Nginx uses. It’s good to set this to the number of CPU cores.
worker_processes auto;
- error_log: Where to save error messages.
error_log /var/log/nginx/error.log warn;
- pid: Specifies the file that holds Nginx’s process ID.
pid /var/run/nginx.pid;
- events: Manages how Nginx handles connections.
events { worker_connections 1024; }
- http: Contains settings for serving web pages.
http { include /etc/nginx/mime.types; default_type application/octet-stream; ... }
- worker_processes: Sets how many processes Nginx uses. It’s good to set this to the number of CPU cores.
- After making changes, save and close the file.
Create a Website with Virtual Hosts
Virtual hosts let you run multiple websites on the same server.
- Create a new configuration file for your website:
sudo vi /etc/nginx/conf.d/example.com.conf
- Add the following content, replacing
example.com
with your domain:server { listen 80; server_name example.com www.example.com; root /var/www/html/example.com; index index.html index.htm index.php; location / { try_files $uri $uri/ =404; } }
- Create the directory for your website:
sudo mkdir -p /var/www/html/example.com
- Set the right permissions:
sudo chown -R nginx:nginx /var/www/html/example.com
- Create a simple web page:
sudo vi /var/www/html/example.com/index.html
Add the following HTML:
<!DOCTYPE html> <html> <head> <title>Welcome to Example.com</title> </head> <body> <h1>Success! Nginx is serving your site.</h1> </body> </html>
- Save and close the file.
Managing the Nginx Service
You can control Nginx using simple commands. Here’s how to start, stop, restart, and check its status.
Start Nginx
To start the Nginx service:
sudo systemctl start nginx
Stop Nginx
To stop the Nginx service:
sudo systemctl stop nginx
Restart Nginx
If you make changes to the configuration, restart Nginx to apply them:
sudo systemctl restart nginx
Check Nginx Status
To see if Nginx is running:
sudo systemctl status nginx
You should see that Nginx is active (running).
Setting Up the Firewall
A firewall helps protect your server. You need to allow web traffic through the firewall.
Understanding FirewallD
CentOS 7 uses FirewallD to manage firewall settings. It lets you open or close ports as needed.
Allow Web Traffic
Allow HTTP (port 80) and HTTPS (port 443) traffic.
- Allow HTTP:
sudo firewall-cmd --permanent --zone=public --add-service=http
- Allow HTTPS:
sudo firewall-cmd --permanent --zone=public --add-service=https
- Reload the firewall to apply changes:
sudo firewall-cmd --reload
Check Firewall Settings
To see what services are allowed:
sudo firewall-cmd --zone=public --list-all
You should see http
and https
under services.
Test Your Nginx Installation
After setting up, make sure everything works.
View the Default Page
- Open a web browser.
- Enter your server’s IP address or domain name, like
http://your_server_ip
orhttp://example.com
. - You should see the Nginx welcome page or the custom page you created.
Fix Common Problems
If you don’t see your website, try these steps:
- Check Nginx Status: Make sure Nginx is running.
sudo systemctl status nginx
- Verify Firewall: Ensure ports 80 and 443 are open.
sudo firewall-cmd --zone=public --list-all
- Test Configuration: Look for mistakes in Nginx settings.
sudo nginx -t
This command checks the configuration for errors.
- Check SELinux: SELinux might block Nginx.
sestatus
If SELinux is enforcing, you might need to adjust its settings or set it to permissive for testing.
Secure Your Nginx Server
Keeping your server secure is important. Here’s how to add security to Nginx.
Add SSL for Security
SSL (Secure Sockets Layer) encrypts data between your server and users.
- Create an SSL Directory:
sudo mkdir -p /etc/nginx/ssl
- Generate a Self-Signed SSL Certificate:
sudo openssl req -newkey rsa:2048 -nodes -keyout /etc/nginx/ssl/example.com.key -x509 -days 365 -out /etc/nginx/ssl/example.com.crt
Follow the prompts to enter your details.
Turn on HTTPS
Update your Nginx configuration to use SSL.
- Open your website’s configuration file:
sudo vi /etc/nginx/conf.d/example.com.conf
- Add a new server block for HTTPS:
server { listen 443 ssl; server_name example.com www.example.com; ssl_certificate /etc/nginx/ssl/example.com.crt; ssl_certificate_key /etc/nginx/ssl/example.com.key; root /var/www/html/example.com; index index.html index.htm index.php; location / { try_files $uri $uri/ =404; } }
- Redirect HTTP to HTTPS by adding this to the HTTP server block:
server { listen 80; server_name example.com www.example.com; return 301 https://$host$request_uri; }
- Save and close the file.
- Test the configuration:
sudo nginx -t
- Restart Nginx to apply changes:
sudo systemctl restart nginx
Follow Security Best Practices
Make your server more secure by following these tips:
- Hide Nginx Version: Prevent others from seeing your Nginx version.
server_tokens off;
- Limit HTTP Methods: Allow only safe methods like GET, POST, and HEAD.
if ($request_method !~ ^(GET|POST|HEAD)$ ) { return 444; }
- Protect Sensitive Files: Block access to hidden files and directories.
location ~ /\.(ht|git|svn) { deny all; }
- Enable Rate Limiting: Prevent too many requests from the same IP.
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s; server { location / { limit_req zone=one burst=20; } }
Make Nginx Run Better
Optimize Nginx to handle more traffic and serve pages faster.
Use Caching
Caching stores copies of your web pages to serve them quickly.
- Enable FastCGI Caching for PHP:
http { ... fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=php_cache:10m inactive=60m; fastcgi_cache_key "$scheme$request_method$host$request_uri"; ... }
- Set Cache Headers for Static Files:
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { expires 30d; add_header Cache-Control "public, no-transform"; }
Balance the Load
Distribute traffic across multiple servers to keep things running smoothly.
- Define Upstream Servers:
upstream backend { server backend1.example.com; server backend2.example.com; server backend3.example.com; }
- Use Upstream in Server Block:
server { listen 80; server_name example.com; location / { proxy_pass http://backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } }
Fine-Tune Settings
Adjust Nginx settings to get the best performance.
- Increase Worker Connections:
events { worker_connections 4096; }
- Enable Gzip Compression: Makes web pages smaller and faster to load.
http { gzip on; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; }
- Adjust Buffer Sizes:
http { client_header_buffer_size 1k; large_client_header_buffers 4 4k; }
Remove Nginx if Needed
If you decide to stop using Nginx, you can remove it from your server.
Uninstall Nginx
- Run the removal command:
sudo yum remove nginx -y
This deletes Nginx and its related packages.
Delete Configuration Files
After uninstalling, remove leftover files to clean up.
- Remove Nginx Config Folder:
sudo rm -rf /etc/nginx
- Delete Website Files:
sudo rm -rf /var/www/html/example.com
- Remove SSL Files (if any):
sudo rm -rf /etc/nginx/ssl
Frequently Asked Questions (FAQ)
Can I install Nginx on CentOS 7 without root privileges?
No. You need root or sudo access to install and set up Nginx.
Is Nginx suitable for high-traffic websites?
Yes. Nginx is designed to handle many visitors at the same time efficiently.
Do I need to enable the EPEL repository to install Nginx?
Yes. The EPEL repository provides the Nginx package for CentOS 7.
Can I secure Nginx with SSL on CentOS 7?
Yes. You can add SSL certificates to secure your Nginx server with HTTPS.
Is FirewallD configured by default on CentOS 7?
Yes. CentOS 7 uses FirewallD by default to manage firewall settings.
Does Nginx support PHP applications?
Yes. Nginx can run PHP applications using PHP-FPM or FastCGI.
Can I run multiple websites on a single Nginx server?
Yes. Nginx supports virtual hosts, letting you host multiple websites on one server.
Is Nginx resource-efficient?
Yes. Nginx uses few system resources while handling many connections.
Can I use Nginx as a reverse proxy on CentOS 7?
Yes. Nginx can act as a reverse proxy to direct traffic to other servers.
Does Nginx support HTTP/2?
Yes. Nginx supports HTTP/2, which makes websites load faster.
Helpful Links
- Official Nginx Documentation
- CentOS 7 Documentation
- Nginx SSL/TLS Setup Guide
- FirewallD Documentation
- Nginx Security Tips
Conclusion
Installing Nginx on CentOS 7 is a straightforward process that can enhance your website’s speed and reliability. By following this simple guide, you can set up a powerful web server, ensure it’s secure, and optimize its performance. Remember to keep your server updated and monitor its performance regularly to maintain a smooth and secure web environment.