How To Install Linux, Nginx, MySQL, PHP (LEMP) stack On CentOS 7 ?

Harry P

Well-known member
Registered
Joined
Feb 3, 2015
Messages
447
Points
28
I only want to install these services for my VPS server to host my website. How can I do this in an easy way? please guide me.
 

MooseLucifer

Well-known member
Registered
Joined
May 20, 2016
Messages
149
Points
28
The benefits of installing the LEMP stack on CentOS 7 include high performance and low memory usage provided by Nginx, optimized performance and security provided by MySQL and CentOS, the flexibility of PHP for building a variety of web applications, cost-effectiveness due to the free and open-source software, and ease of management and configuration with a wealth of documentation and tutorials available online.

Here is a step-by-step guide on how to install the LEMP stack on CentOS 7.

Prerequisites
Before you start, make sure you have the following:
  • A server running CentOS 7.
  • A user account with sudo privileges.
  • A terminal application (such as PuTTY for Windows users) to access the server.
Step 1: Update the system
First, update the system to ensure you have the latest packages and security updates:

Code:
sudo yum update
Step 2: Install Nginx
Nginx is a lightweight web server that is used to serve static content, reverse proxy, and load balance HTTP traffic. To install Nginx on CentOS 7, run the following command:

Code:
sudo yum install nginx
After the installation is complete, start the Nginx service and enable it to start automatically at boot:

Code:
sudo systemctl start nginx
sudo systemctl enable nginx
To check if Nginx is running, open your web browser and enter your server's IP address in the address bar. You should see the default Nginx web page.

Step 3: Install MySQL
MySQL is a popular open-source database management system. To install MySQL on CentOS 7, run the following command:

Code:
sudo yum install mysql-server
After the installation is complete, start the MySQL service and enable it to start automatically at boot:

Code:
sudo systemctl start mysqld
sudo systemctl enable mysqld
Run the following command to secure your MySQL installation:

Code:
sudo mysql_secure_installation
This will prompt you to set a root password, remove anonymous users, disallow remote root login, and remove the test database. Follow the prompts to complete the process.

Step 4: Install PHP
PHP is a popular programming language used to build dynamic web applications. To install PHP on CentOS 7, run the following command:

Code:
sudo yum install php php-mysql
After the installation is complete, restart the Nginx service to load the PHP module:

Code:
sudo systemctl restart nginx
Step 5: Test the LEMP stack
To test the LEMP stack, create a PHP file in the Nginx web root directory:

Code:
sudo nano /usr/share/nginx/html/info.php
Add the following code to the file:

Code:
<?php
phpinfo();
?>
Save and close the file. Then, open your web browser and enter the following URL:

Code:
http://<your-server-ip-address>/info.php
You should see a page with information about your PHP installation.

Conclusion
Congratulations! You have successfully installed the LEMP stack on CentOS 7. You now have a powerful web server that can serve static content, run dynamic web applications, and manage databases.
 

Harry P

Well-known member
Registered
Joined
Feb 3, 2015
Messages
447
Points
28
Great post @MooseLucifer

but now i want to add my website (domain name) into this LEMP stack, how can I do that? how to configure to make my website appear online on the internet?
 

MooseLucifer

Well-known member
Registered
Joined
May 20, 2016
Messages
149
Points
28
MooseLucifer
To add your website (domain name) to the LEMP stack, you need to perform the following steps:

Point your domain name to your server's IP address: This can be done by configuring the DNS records of your domain name to point to your server's IP address. You can do this through your domain registrar's control panel.

Create a new server block in Nginx: A server block is a configuration file that tells Nginx how to handle incoming HTTP requests for a particular domain name. To create a new server block, create a new file in the /etc/nginx/conf.d/ directory with the name of your domain name, followed by the .conf extension. For example, if your domain name is example.com, you can create a file called /etc/nginx/conf.d/example.com.conf.

Configure the server block: In the server block configuration file, you need to specify the server name (your domain name), the root directory of your website's files, and any other directives specific to your website. Here's an example configuration file:

Code:
server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;
    root /var/www/example.com;
    index index.php index.html;
   
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
   
    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}
This configuration file tells Nginx to listen on port 80 for incoming HTTP requests for example.com and www.example.com. The root directive specifies the root directory of your website's files, and the index directive specifies the default index file to serve. The location directives specify how to handle incoming HTTP requests for static files (such as HTML, CSS, and JavaScript files) and PHP files.

Restart Nginx: After you've created and configured the server block, you need to restart Nginx to apply the changes. You can do this with the following command:
Code:
sudo systemctl restart nginx
Test your website: Finally, you can test your website by entering your domain name in a web browser. If everything is configured correctly, you should see your website appear online on the internet.

Note: Make sure to place your website files in the root directory specified in your Nginx configuration file, and configure your database settings in your PHP code if your website requires a database.
 

Harry P

Well-known member
Registered
Joined
Feb 3, 2015
Messages
447
Points
28
Harry P
How can I add database for my website? for example after created a mysql database, I want to manage it with phpmyadmin. How can I achieve that?
 

MooseLucifer

Well-known member
Registered
Joined
May 20, 2016
Messages
149
Points
28
MooseLucifer
To add a database for your website on the LEMP stack and manage it with phpMyAdmin, you need to perform the following steps:

Install MySQL: First, you need to install MySQL on your CentOS 7 server. You can do this by running the following command:
Code:
sudo yum install mysql-server
Secure MySQL: After installing MySQL, you should secure it by running the mysql_secure_installation script. This script will prompt you to set the root password, remove anonymous users, disallow root login remotely, and remove test databases. You can run the script by typing the following command:

Code:
sudo mysql_secure_installation
Create a database and user: After securing MySQL, you can create a new database and user for your website. You can do this by logging into the MySQL shell with the root account and running the following commands:

Code:
mysql -u root -p

CREATE DATABASE example_database;
GRANT ALL PRIVILEGES ON example_database.* TO 'example_user'@'localhost' IDENTIFIED BY 'password';
FLUSH PRIVILEGES;
exit
Replace example_database with the name of your database, example_user with the name of your user, and password with a strong password.

Install phpMyAdmin: Next, you need to install phpMyAdmin on your server. You can do this by running the following command:

Code:
sudo yum install epel-release
sudo yum install phpmyadmin
During the installation process, you will be prompted to configure phpMyAdmin to work with your web server. Choose Nginx as your web server, and set the document root to /usr/share/phpMyAdmin/.

Configure phpMyAdmin: After installing phpMyAdmin, you need to configure it to work with your MySQL database. You can do this by editing the config.inc.php file in the /etc/phpMyAdmin/ directory. Replace the existing configuration with the following:

Code:
<?php
/* Servers configuration */
$i = 0;
/* Server: localhost [1] */
$i++;
$cfg['Servers'][$i]['verbose'] = 'Localhost';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['port'] = '';
$cfg['Servers'][$i]['socket'] = '';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = 'example_user';
$cfg['Servers'][$i]['password'] = 'password';
$cfg['Servers'][$i]['AllowNoPassword'] = false;
?>
Replace example_user with the name of the user you created in step 3, and password with the password you set for that user.

Restart Nginx: After configuring phpMyAdmin, you need to restart Nginx to apply the changes. You can do this with the following command:

Code:
sudo systemctl restart nginx
Access phpMyAdmin: Finally, you can access phpMyAdmin by entering http://your_server_ip/phpmyadmin in a web browser. You should see the phpMyAdmin login screen, where you can log in with the user credentials you created in step 3. From there, you can manage your MySQL database and perform tasks such as creating tables, adding data, and running SQL queries.
 
Last edited:

Harry P

Well-known member
Registered
Joined
Feb 3, 2015
Messages
447
Points
28
Harry P
I want to install a simple mail server so that my website can send and receive mail from this LEMP server. is that possible? how can I do that and how to install and configure to have a mail server for mailing?
 

MooseLucifer

Well-known member
Registered
Joined
May 20, 2016
Messages
149
Points
28
MooseLucifer
Yes, it is possible to install a simple mail server on your LEMP stack so that your website can send and receive emails. Here's how to do it:

Install Postfix: Postfix is a popular open-source mail transfer agent (MTA) that can be used to send and receive emails. You can install it on your CentOS 7 server by running the following command:

Code:
sudo yum install postfix
Configure Postfix: After installing Postfix, you need to configure it to work with your domain name. Edit the /etc/postfix/main.cf file and add the following lines at the end:

Code:
myhostname = example.com
mydomain = example.com
myorigin = $mydomain
inet_interfaces = all
mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
mynetworks = 127.0.0.0/8
home_mailbox = Maildir/
Replace example.com with your own domain name. These settings will tell Postfix to accept emails for your domain name, and deliver them to the Maildir directory in the home directory of the recipient.

Restart Postfix: After configuring Postfix, you need to restart it to apply the changes. You can do this with the following command:

Code:
sudo systemctl restart postfix
Install Dovecot: Dovecot is a popular open-source IMAP and POP3 server that can be used to retrieve emails from a remote mail server. You can install it on your CentOS 7 server by running the following command:

Code:
sudo yum install dovecot
Configure Dovecot: After installing Dovecot, you need to configure it to work with Postfix. Edit the /etc/dovecot/dovecot.conf file and add the following lines at the end:

Code:
protocols = imap pop3
mail_location = maildir:~/Maildir
auth_mechanisms = plain login
These settings will tell Dovecot to use the Maildir directory in the home directory of the user to store emails, and allow users to authenticate with their email address and password.

Restart Dovecot: After configuring Dovecot, you need to restart it to apply the changes. You can do this with the following command:

Code:
sudo systemctl restart dovecot
Test the mail server: To test your mail server, you can use a command-line tool like mailx. Install it on your CentOS 7 server by running the following command:

Code:
sudo yum install mailx
You can then send a test email to yourself with the following command:

Code:
echo "This is a test email" | mail -s "Test email" [email protected]
Replace [email protected] with your own email address. You should receive the email in your inbox if everything is working correctly.

With these steps, you have installed and configured a simple mail server on your LEMP stack. You can now use your website to send and receive emails using your own domain name.
 

Harry P

Well-known member
Registered
Joined
Feb 3, 2015
Messages
447
Points
28
Harry P
Great explanation!

I heard that NGinx has a great caching to speed up website. how can i install and configure it for better performance?
 

MooseLucifer

Well-known member
Registered
Joined
May 20, 2016
Messages
149
Points
28
MooseLucifer
Yes, Nginx has a powerful caching mechanism that can significantly improve the performance of your website. Here's how to install and configure Nginx caching on CentOS 7:

Install Nginx: If you haven't already, install Nginx on your CentOS 7 server with the following command:

Code:
sudo yum install nginx
Enable caching in Nginx: By default, Nginx does not cache any content. To enable caching, you need to add the following lines to your Nginx configuration file (/etc/nginx/nginx.conf):

Code:
http {
    # ...

    proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m;
    proxy_cache_key "$scheme$request_method$host$request_uri";
    proxy_cache_valid 200 60m;
    proxy_cache_valid 404 1m;
    proxy_cache_bypass $http_pragma;
    proxy_cache_revalidate on;
    proxy_cache_min_uses 1;
    proxy_cache_lock on;
}
These settings will enable caching in Nginx, and store cached content in the /var/cache/nginx directory. The proxy_cache_valid directive specifies how long cached content should be considered fresh, and the proxy_cache_min_uses directive specifies how many times a resource needs to be requested before it is cached.

Configure Nginx to cache specific content: By default, Nginx will cache any content that is returned with a 200 status code. However, you may want to cache specific content based on its URL or content type. To do this, you can use the proxy_cache_key directive and add it to specific location blocks in your Nginx configuration file. For example:

Code:
location / {
    proxy_pass http://backend;
    proxy_cache my_cache;
    proxy_cache_key "$scheme$request_method$host$request_uri$args";
}
This location block will cache all content that is requested from the root of your website (/). You can customize the proxy_cache_key directive to cache content based on its URL, content type, or any other relevant criteria.

Monitor the caching performance: Once you have enabled caching in Nginx, you can monitor its performance using the nginx-cache-purge module. Install it with the following command:

Code:
sudo yum install nginx-module-cache-purge
You can then use the cache-purge command-line tool to inspect the contents of the cache, and invalidate cached content if necessary.

Now, you have installed and configured Nginx caching on your CentOS 7 server. This will significantly improve the performance of your website, especially for frequently requested content.
 

MooseLucifer

Well-known member
Registered
Joined
May 20, 2016
Messages
149
Points
28
MooseLucifer
To integrate Nginx caching with your WordPress website, follow these steps:

Install the Nginx Helper plugin: This plugin will enable WordPress to interact with the Nginx caching system. You can install it from the WordPress plugin repository, or by uploading the plugin files to your server. Once installed, activate the plugin.

Enable caching in the Nginx Helper plugin: Go to the Nginx Helper settings page in your WordPress admin panel, and check the box next to "Enable Purge". This will allow WordPress to invalidate cached content when it is updated.

Configure the Nginx caching rules: In your Nginx configuration file, add a location block for the WordPress site that specifies the caching rules. For example:

Code:
location / {
    proxy_pass http://backend;
    proxy_cache my_cache;
    proxy_cache_key "$scheme$request_method$host$request_uri$args";
    proxy_cache_valid 200 60m;
    proxy_cache_valid 404 1m;
    proxy_cache_bypass $http_pragma;
    proxy_cache_revalidate on;
    proxy_cache_min_uses 1;
    proxy_cache_lock on;

    # WordPress-specific rules
    set $skip_cache 0;
    if ($request_method = POST) {
        set $skip_cache 1;
    }
    if ($query_string != "") {
        set $skip_cache 1;
    }
    if ($http_cookie ~* "comment_author_|wordpress_(?!test_cookie)|wp-postpass_" ) {
        set $skip_cache 1;
    }
    if ($http_user_agent ~* "(iPhone|iPad|Android|BlackBerry)") {
        set $skip_cache 1;
    }
    if ($skip_cache = 0) {
        add_header X-Cache-Status $upstream_cache_status;
    }
}
This location block will cache all content that is requested from the root of your WordPress site (/). The WordPress-specific rules will prevent certain content from being cached, such as content from logged-in users or mobile devices.

Test the caching: Once you have configured the Nginx caching rules, you can test the caching by accessing your WordPress site and inspecting the headers. Look for the X-Cache-Status header, which should indicate whether the content was served from cache (HIT) or generated on the fly (MISS).

Now, you have integrated Nginx caching with your WordPress website. This will significantly improve the performance of your site, especially for frequently requested content.
 

Harry P

Well-known member
Registered
Joined
Feb 3, 2015
Messages
447
Points
28
Harry P
I heard that htaccess file will not work on nginx so that rewrite urls will not work and my wordpress site can not work too. how to enable rewrite rules or make my site work with htaccess file?
 

MooseLucifer

Well-known member
Registered
Joined
May 20, 2016
Messages
149
Points
28
MooseLucifer
That's correct, Nginx doesn't use .htaccess files like Apache does, so the rewrite rules that are typically placed in a WordPress .htaccess file won't work out of the box. However, Nginx has its own way of handling URL rewriting, using a configuration file.

To enable rewrite rules for WordPress on Nginx, you need to:
  • Locate the Nginx configuration file for your WordPress site. This file is typically located in the /etc/nginx/sites-available/ directory.
  • Open the Nginx configuration file in your text editor.
  • Locate the location / block in the configuration file. This is the block that specifies the root directory for your WordPress site.
  • Add the following lines inside the location / block:
Code:
try_files $uri $uri/ /index.php?$args;
This line tells Nginx to first try to serve the requested URL as a file, then as a directory, and if neither of those exist, to pass the request to index.php with any query string parameters attached.
  • Add the following lines just above the location / block:
Code:
rewrite /wp-admin$ $scheme://$host$uri/ permanent;
This line is optional, but it is recommended to add it to redirect any requests to /wp-admin to use HTTPS.
  • Save the configuration file and exit the text editor.
  • Test the configuration by running the following command:
Code:
sudo nginx -t
This will check the syntax of your Nginx configuration file and alert you to any errors.
  • If the test command reports no errors, reload the Nginx configuration by running the following command:
Code:
sudo systemctl reload nginx
With these steps, you have enabled rewrite rules for WordPress on Nginx, which should allow your WordPress site to work correctly.
 

Harry P

Well-known member
Registered
Joined
Feb 3, 2015
Messages
447
Points
28
Harry P
i feel difficult to add or enable https on LEMP, I am using cloudflare, is there a way to add certificate keys..etc to enable HTTPS for my Wordpress website on Nginx?
 

MooseLucifer

Well-known member
Registered
Joined
May 20, 2016
Messages
149
Points
28
MooseLucifer
Enabling HTTPS on a WordPress site running on Nginx can be a bit tricky, but with Cloudflare, you can simplify the process by using Cloudflare's SSL certificate. Here's how you can configure HTTPS on your WordPress site running on Nginx with Cloudflare:
  • Login to your Cloudflare account and select the domain you want to enable HTTPS for.
  • Go to the SSL/TLS tab and make sure that the SSL mode is set to "Full" or "Full (strict)".
  • Generate a new origin certificate by clicking on the "Origin Server" section under "Origin Certificates" and follow the instructions to generate a new certificate.
  • After generating the certificate, copy the contents of the "Origin Certificate" and "Private Key" fields and save them to a text file.
  • SSH into your server and navigate to the directory where you want to store the certificate files. For example, you can create a directory /etc/nginx/certs and store the files there.
  • Create a new file in the directory and paste the contents of the origin certificate into it. Name the file something like example.com.pem.
  • Create another file in the directory and paste the contents of the private key into it. Name the file something like example.com.key.
  • Modify your Nginx configuration file for your WordPress site to include the SSL certificate files. You can do this by adding the following lines inside the server block:
Code:
listen 443 ssl;
ssl_certificate /etc/nginx/certs/example.com.pem;
ssl_certificate_key /etc/nginx/certs/example.com.key;
Make sure to replace example.com with your actual domain name.
  • Save the configuration file and test it for syntax errors by running the following command:
Code:
sudo nginx -t
  • If the test command reports no errors, reload Nginx to apply the changes by running the following command:
Code:
sudo systemctl reload nginx
You should now have HTTPS enabled for your WordPress site running on Nginx with Cloudflare.
 

Paul Wellner Bou

Well-known member
Registered
Joined
Apr 20, 2016
Messages
95
Points
6
Interesting discussion, I want to ask which is default PHP version and mySQL version of LEMP server? and if it is old version, how can I upgrade PHP or MySQL to custom version that I want?
 

MooseLucifer

Well-known member
Registered
Joined
May 20, 2016
Messages
149
Points
28
MooseLucifer
The default PHP and MySQL versions on a LEMP server can vary depending on the Linux distribution and version being used. However, most modern LEMP server setups will come with PHP 7.x and MySQL 5.7 or 8.x installed. If the default versions are old and you want to upgrade, you can follow a few simple steps.

First, check the current version of PHP and MySQL on your server using the appropriate commands. Once you know which versions you're running, you can add the repositories for the newer versions you want to install. You can usually find instructions for doing this on the official websites of PHP and MySQL.

Next, install the newer versions of PHP and MySQL using the appropriate commands for your Linux distribution. For example, on Ubuntu, you can use the sudo apt-get install command to install PHP 8.0 or MySQL 8.0.

After installing the new versions, you may need to configure your Nginx server to use the new version of PHP. This can be done by updating the relevant Nginx configuration files. Once you've made the necessary changes, restart the Nginx server to apply the updates.

It's important to note that upgrading to a newer version of PHP or MySQL may require you to update any code or applications that rely on those services. Be sure to thoroughly test your applications after upgrading to ensure everything is working as expected.

Upgrading PHP or MySQL on a LEMP server can be done by checking the current versions, adding repositories for the new versions, installing the new versions, updating the Nginx configuration files, and restarting the Nginx server. However, it's important to test your applications thoroughly after upgrading to ensure everything is working as expected.
 

BlueLeaf

Well-known member
Registered
Joined
Apr 11, 2017
Messages
168
Points
18
To check the default PHP version, you can run the following command in your terminal:

Code:
php -v
To check the default MySQL version, you can run the following command in your terminal:

Code:
mysql -V
 

Dopani

Well-known member
Registered
Joined
Mar 11, 2014
Messages
233
Points
18
Dopani
I am curious if I upgrade php version to 7.4 (for example) then I can downgrade it back to 7.0 or 7.2 if wanted?
 

MooseLucifer

Well-known member
Registered
Joined
May 20, 2016
Messages
149
Points
28
MooseLucifer
Yes, in most cases, you should be able to downgrade the PHP version on a LEMP stack if needed. However, it's important to keep in mind that the specific steps to do so may vary depending on the Linux distribution and version being used.

If you're using a package manager like apt-get or yum to manage your PHP installation, you can typically use the same commands to downgrade to a previous version as you would to upgrade to a newer version. For example, to downgrade from PHP 7.4 to PHP 7.2 on Ubuntu, you could use the following command:

Code:
sudo apt-get install php7.2
After installing the older version of PHP, you may need to update your Nginx server configuration to use the older version. Once you've made the necessary changes, restart the Nginx server to apply the updates.

It's worth noting that downgrading to an older version of PHP may result in compatibility issues with some applications or libraries that require a newer version. Therefore, it's important to thoroughly test your applications after downgrading to ensure everything is working as expected. Additionally, it's always a good idea to make a backup of your server before making any major changes to your software stack.
 

MooseLucifer

Well-known member
Registered
Joined
May 20, 2016
Messages
149
Points
28
MooseLucifer
Hello, this is a general guideline for updating your Nginx server configuration to use the older version of PHP after downgrading. Here are the steps you can follow:
  1. Locate the PHP-FPM configuration file for Nginx. This file is typically named php-fpm.conf or www.conf and is located in the /etc/php/<version>/fpm/pool.d/ directory.
  2. Open the PHP-FPM configuration file in a text editor and update the listen parameter to reflect the port number used by the older version of PHP. For example, if you downgraded to PHP 7.2, the default port number is 9000. So, you would update the listen parameter to listen = 127.0.0.1:9000.
  3. Save the changes to the PHP-FPM configuration file and exit the text editor.
  4. Open the Nginx configuration file in a text editor. This file is typically located in the /etc/nginx/ directory and is named nginx.conf.
  5. Locate the location ~ \.php$ block in the Nginx configuration file. This block defines how Nginx handles PHP requests.
  6. Update the fastcgi_pass parameter in the location ~ \.php$ block to reflect the new PHP-FPM configuration file. For example, if the PHP-FPM configuration file is named www.conf, you would update the fastcgi_pass parameter to fastcgi_pass unix:/run/php/php7.2-fpm.sock;
  7. Save the changes to the Nginx configuration file and exit the text editor.
  8. Restart the Nginx server to apply the updates using the following command:
Code:
sudo systemctl restart nginx
Now your Nginx server should now be configured to use the older version of PHP. However, keep in mind that downgrading to an older version of PHP may cause compatibility issues with some applications or libraries that require a newer version. So, it's important to thoroughly test your applications after downgrading to ensure everything is working as expected.
 
Newer Threads
Latest Threads
Recommended Threads

Latest Hosting OffersNew Reviews

Sponsors

Tag Cloud

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top