Tutorial

How To Install Nginx on CentOS 7

Updated on January 25, 2022
How To Install Nginx on CentOS 7
Not using CentOS 7?Choose a different version or distribution.
CentOS 7

Introduction

Nginx is a popular high-performance web server. This tutorial will teach you how to install and start Nginx on your CentOS 7 server.

Prerequisites

The steps in this tutorial require a non-root user with sudo privileges. See our Initial Server Setup with CentOS 7 tutorial to learn how to set up this user.

Step 1 — Adding the EPEL Software Repository

To add the CentOS 7 EPEL repository, first connect to your CentOS 7 machine via SSH, then use the yum command to install the extended package repository:

  1. sudo yum install epel-release

You’ll be prompted to verify that you want to install the software. Type y then ENTER to continue.

Next, you’ll install the actual nginx software package.

Step 2 — Installing Nginx

Now that the EPEL repository is installed on your server, install Nginx using the following yum command:

  1. sudo yum install nginx

Again, answer yes to the verification prompt, then Nginx will finish installing.

Step 3 — Starting Nginx

Nginx will not start automatically after it is installed. To get Nginx running, use the systemctl command:

  1. sudo systemctl start nginx

You can check the status of the service with systemctl status:

  1. sudo systemctl status nginx
Output
● nginx.service - The nginx HTTP and reverse proxy server Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; vendor preset: disabled) Active: active (running) since Mon 2022-01-24 20:14:24 UTC; 5s ago Process: 1898 ExecStart=/usr/sbin/nginx (code=exited, status=0/SUCCESS) Process: 1896 ExecStartPre=/usr/sbin/nginx -t (code=exited, status=0/SUCCESS) Process: 1895 ExecStartPre=/usr/bin/rm -f /run/nginx.pid (code=exited, status=0/SUCCESS) Main PID: 1900 (nginx) CGroup: /system.slice/nginx.service ├─1900 nginx: master process /usr/sbin/nginx └─1901 nginx: worker process Jan 24 20:14:24 centos-updates systemd[1]: Starting The nginx HTTP and reverse proxy server... Jan 24 20:14:24 centos-updates nginx[1896]: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok Jan 24 20:14:24 centos-updates nginx[1896]: nginx: configuration file /etc/nginx/nginx.conf test is successful Jan 24 20:14:24 centos-updates systemd[1]: Started The nginx HTTP and reverse proxy server.

The service should be active.

If you are running a firewall, run the following commands to allow HTTP and HTTPS traffic:

  1. sudo firewall-cmd --permanent --zone=public --add-service=http
  2. sudo firewall-cmd --permanent --zone=public --add-service=https
  3. sudo firewall-cmd --reload

You can do a spot check right away to verify that everything went as planned by visiting your server’s public IP address in your web browser:

http://server_domain_name_or_IP/

You will see the default CentOS 7 Nginx web page, which is there for informational and testing purposes. It should look something like this:

CentOS 7 Nginx Default

If you see this page, then your web server is now correctly installed.

Note: To find your server’s public IP address, find the network interfaces on your machine by typing:

  1. ip addr
Output
1. lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN . . . 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000 . . .

You may see a number of interfaces here depending on the hardware available on your server. The lo interface is the local loopback interface, which is not the one we want. In our example above, the eth0 interface is what we want.

Once you have the interface name, you can run the following command to reveal your server’s public IP address. Substitute the interface name you found above:

  1. ip addr show eth0 | grep inet | awk '{ print $2; }' | sed 's/\/.*$//'

Before continuing, you will probably want to enable Nginx to start when your system boots. To do so, enter the following command:

  1. sudo systemctl enable nginx

Nginx is now installed and running.

Step 4 — Exploring and Configuring Nginx

If you want to start serving your own pages or application through Nginx, you will want to know the locations of the Nginx configuration files and default server root directory.

Default Server Root

The default server root directory is /usr/share/nginx/html. Files that are placed in there will be served on your web server. This location is specified in the default server block configuration file that ships with Nginx, which is located at /etc/nginx/conf.d/default.conf.

Server Block Configuration

Any additional server blocks, known as Virtual Hosts in Apache, can be added by creating new configuration files in /etc/nginx/conf.d. Files that end with .conf in that directory will be loaded when Nginx is started.

Nginx Global Configuration

The main Nginx configuration file is located at /etc/nginx/nginx.conf. This is where you can change settings like the user that runs the Nginx daemon processes, and the number of worker processes that get spawned when Nginx is running, among other things.

Conclusion

Once you have Nginx installed on your CentOS 7 server, you can go on to install the full LEMP Stack on CentOS 7.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Mitchell Anicas
Mitchell Anicas
See author profile
Category:
Tutorial

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
23 Comments
Leave a comment...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Thanks for the writeup!

There seems to be a typo here:

sudo servicectl enable nginx.service

(should be systemctl)

you beat me to it Zubin! :)

Andrew SB
DigitalOcean Employee
DigitalOcean Employee badge
August 7, 2014

Good catch! Updated.

Thanks for the guide, personally I prefer source compiled Nginx for the flexibility in installing additional Nginx modules like ngx_pagespeed etc https://community.centminmod.com/threads/centmin-mod-nginx-lnmp-install-on-centos-7-0-kvm-vps.1202/

Mitchell,

You forgot to mention adjusting the firewall rules. Centos and Redhat enable the firewalls by default and they will block access to port 80.

So users will need add a iptables rule of firewalld rule depending on the version of Cent

For some reason, even though I’m definitely using Centos 7, the nginx default page says “Welcome to nginx on Fedora”…

I tried it using the default yum repo as well as the one mentioned in the article.

I know it’s probably nothing but just a bit weird- anyone else experienced this? I can’t imagine my server will up and explode because of it, but it’s a constant worry :P

Chances are it’s showing “Welcome to nginx on Fedora” because nginx is built as part of the EPEL, which is built using a configuration intended for Fedora.

How to stop Nginx on CentOS 7 ? And What is the best way to reload Nginx config without restart?

Thanks

I find another way of installing Nginx. Centmin mod is a shell script which has ability to install Nginx, MariaDB/MySQL, PHP and DNS on a server. I installed Centmin mod using this article.

Like mentioned it does say fedora but thats not a problem.

I tried following the instructions aboyve, however, i do get this ( after the final step ):

Job for nginx.service failed because the control process exited with error code. See “systemctl status nginx.service” and “journalctl -xe” for details.

Anyone on how to solve this issue ?

@schuitman70 Run the following command to test your nginx config and it will tell you what is wrong: “nginx -t” (usually it’s something in your “nginx.conf” file).

Nice tutorial, worked like a charm!

It seems everything is covered here. Do you think choosing Nginx over Apache buys me anything with a multi-domain Wordpress droplet?

KFSys
Site Moderator
Site Moderator badge
July 31, 2024

Heya,

Nginx vs. Apache for High-Traffic WordPress Sites

Performance and Scalability

  • Nginx:

    • Event-Driven Architecture: Nginx uses an event-driven, asynchronous architecture, which allows it to handle many concurrent connections efficiently. This makes Nginx highly scalable and capable of serving a large number of simultaneous requests with low memory usage.
    • Static Content Handling: Nginx excels at serving static content (e.g., images, CSS, JavaScript) quickly and efficiently. This reduces the load on the PHP backend, improving overall performance.
    • Low Resource Consumption: Nginx is optimized for low CPU and memory usage, making it suitable for high-traffic environments.
  • Apache:

    • Process-Driven Architecture: Apache uses a process-driven model, where each connection requires its own thread or process. This can lead to higher memory usage and less efficient handling of a large number of concurrent connections.
    • Modules: Apache’s modular architecture allows for extensive customization and flexibility. However, this can also introduce overhead and complexity, potentially affecting performance under high load.

Caching

  • Nginx:

    • FastCGI Caching: Nginx can use FastCGI caching to cache dynamic content generated by PHP, significantly reducing the load on the PHP backend and database.
    • Reverse Proxy Caching: Nginx’s built-in caching mechanisms can cache responses from upstream servers, further improving performance.
  • Apache:

    • mod_cache: Apache offers caching through modules like mod_cache and mod_cache_disk, but these are generally considered less efficient and more complex to configure than Nginx’s caching mechanisms.

Ease of Configuration

  • Nginx:

    • Simpler Configuration for Static Content: Nginx configurations for serving static content and reverse proxying are straightforward and efficient.
    • Less Overhead: Nginx configurations are generally less complex, leading to easier management and fewer potential performance issues.
  • Apache:

    • Extensive Configuration Options: Apache provides a wide range of configuration options through .htaccess files and modules. While this offers flexibility, it can also lead to performance overhead and complexity.
    • Dynamic Configuration: Apache’s use of .htaccess files allows for dynamic configuration without restarting the server, but this can introduce performance penalties.

Compatibility and Ecosystem

  • Nginx:

    • Modern Web Technologies: Nginx is designed with modern web technologies in mind and is commonly used in conjunction with technologies like PHP-FPM, Redis, and various caching solutions.
    • Growing Ecosystem: Nginx has a growing ecosystem and strong community support, with many resources available for optimizing WordPress performance.
  • Apache:

    • Wide Compatibility: Apache is highly compatible with a wide range of applications and technologies. It has been around longer and has extensive documentation and community support.
    • Legacy Support: Apache may be preferred in environments with legacy applications and configurations that require specific modules or features.

Real-World Considerations

Use Cases for Nginx

  • High Traffic: Nginx is well-suited for sites with high traffic volumes due to its efficient handling of concurrent connections and low resource usage.
  • Static Content: Sites that serve a lot of static content will benefit from Nginx’s optimized static content handling.
  • Caching Needs: Sites that can benefit from reverse proxy caching or FastCGI caching will find Nginx’s capabilities advantageous.

Use Cases for Apache

  • Legacy Applications: Sites with legacy applications or configurations that depend on specific Apache modules may prefer Apache.
  • Dynamic Configuration: Environments that require frequent dynamic changes to configuration settings without server restarts might benefit from Apache’s .htaccess capabilities.

Conclusion

For high-traffic WordPress sites, Nginx is generally the better choice due to its superior performance, scalability, and efficient handling of static content and caching. However, if you have specific requirements that necessitate Apache’s features or if you’re dealing with legacy systems, Apache might still be a viable option.

To maximize performance, many high-traffic WordPress sites use a combination of Nginx and Apache in a reverse proxy setup, leveraging the strengths of both servers. In this setup, Nginx handles incoming requests, serves static content, and proxies dynamic requests to Apache running the PHP backend.

Has anyone managed to make this work with Cpanel?

KFSys
Site Moderator
Site Moderator badge
July 30, 2024

Heya,

you shouldn’t install software like that when using cPanel, there are articles on cPanel how to make Nginx work with it as by default it works with Apache.

SELINUX is enabled on the Digital Ocean droplet. This will interfere with nginx. You need to disable it or set up a policy.

This guide is a few years old, so perhaps SELINUX was always enabled by default.

KFSys
Site Moderator
Site Moderator badge
July 30, 2024

That is correct, Selinux will mess with your Nginx, you’ll need to disable it.

Good catch! Updated… thanks for sharing…

You forgot to mention adjusting the firewall rules.I find another way of installing Nginx. I tried following the instructions step by step.

KFSys
Site Moderator
Site Moderator badge
July 30, 2024

Heya,

That is correct, you’ll need to adjust your Firewall to allow access on port 80 and 443. It really depends on what Firewall you are using, either Iptables, firewalld or something else.

Thanks for this information which helps to install nginx within 3 to 4 steps

Wow Great Information. I read your blog very useful and helpful to me. Thanksr sharing it. getintopc

Mitchell,

Thanks for sharing such good and informative content, It does really help. Please keep it continue.

Thanks again,

Nisha

How to upload files on that after installation? and how to protect files or hotlink them? only my domain allowed…

KFSys
Site Moderator
Site Moderator badge
July 30, 2024

Heya,

You’ll need to use an FTP service like FileZilla or use SCP/Rsync with SSH to upload the files.

Alternatively, you can create your App to upload files.

Hello Mitchell,

To be very honest, it’s an awesome step-by-step guide but it seems you might forget to mention firewall adjusting rules. I think Redhat &Centos enable the firewalls by default and they will block access to port 80. Try to do the needful.

Thanks,

Angelina S

KFSys
Site Moderator
Site Moderator badge
July 30, 2024

That is correct, you’ll need to allow port 80 and 443 on whatever firewall you might be using.

Hi All, I was able to install Nginx successfully, but I could not start the web server. BTW, in the text below, Ip-ip-… or xxxx-… are placeholder for the actual IP address of my droplet.


[root@xxxx… ~]# sudo systemctl start nginx Job for nginx.service failed because the control process exited with error code. See “systemctl status nginx.service” and “journalctl -xe” for details.

So I did as instructed and I see this:

[root@xxx ~]# systemctl status nginx.service ● nginx.service - The nginx HTTP and reverse proxy server Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; vendor preset: disabled) Active: failed (Result: exit-code) since Thu 2021-11-11 17:10:28 UTC; 31s ago Process: 12621 ExecStart=/usr/sbin/nginx (code=exited, status=1/FAILURE) Process: 12618 ExecStartPre=/usr/sbin/nginx -t (code=exited, status=0/SUCCESS) Process: 12615 ExecStartPre=/usr/bin/rm -f /run/nginx.pid (code=exited, status=0/SUCCESS)

Nov 11 17:10:26 ip-ip-ip-ip.cprapid.com nginx[12621]: nginx: [emerg] bind() to [::]:80 failed …e) Nov 11 17:10:27 ip-ip-ip-ip.cprapid.com nginx[12621]: nginx: [emerg] bind() to 0.0.0.0:80 fail…e) Nov 11 17:10:27 ip-ip-ip-ip.cprapid.com nginx[12621]: nginx: [emerg] bind() to [::]:80 failed …e) Nov 11 17:10:27 ip-ip-ip-ip.cprapid.com nginx[12621]: nginx: [emerg] bind() to 0.0.0.0:80 fail…e) Nov 11 17:10:27 ip-ip-ip-ip.cprapid.com nginx[12621]: nginx: [emerg] bind() to [::]:80 failed …e) Nov 11 17:10:28 ip-ip-ip-ip.cprapid.com systemd[1]: nginx.service: control process exited, cod…=1 Nov 11 17:10:28 ip-ip-ip-ip.cprapid.com nginx[12621]: nginx: [emerg] still could not bind() Nov 11 17:10:28 ip-ip-ip-ip.cprapid.com systemd[1]: Failed to start The nginx HTTP and reverse…r. Nov 11 17:10:28 ip-ip-ip-ip.cprapid.com systemd[1]: Unit nginx.service entered failed state. Nov 11 17:10:28 ip-ip-ip-ip.cprapid.com systemd[1]: nginx.service failed. Hint: Some lines were ellipsized, use -l to show in full.

Someone advised to do the next:

root@xx…# nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful

Also this:

[root@ip-ip-ip-ip ~]# sudo netstat -plutn | grep :80 tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 4018/httpd
tcp6 0 0 :::80 :::* LISTEN 4018/httpd

I exited out the console and loggin again, and tried. Same result.

So I am stumped! Any advice would be greatly appreciated

KFSys
Site Moderator
Site Moderator badge
July 30, 2024

Heya,

You have Apache installed and running on port 80 this is why you can’t start Nginx on that port

This comment has been deleted

    Join the Tech Talk
    Success! Thank you! Please check your email for further details.

    Please complete your information!

    Become a contributor for community

    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

    DigitalOcean Documentation

    Full documentation for every DigitalOcean product.

    Resources for startups and SMBs

    The Wave has everything you need to know about building a business, from raising funding to marketing your product.

    Get our newsletter

    Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

    New accounts only. By submitting your email you agree to our Privacy Policy

    The developer cloud

    Scale up as you grow — whether you're running one virtual machine or ten thousand.

    Get started for free

    Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

    *This promotional offer applies to new accounts only.