如何在具有PHP和MySQL的CentOS 7.6上安装Nginx(LEMP堆栈)

如何在具有PHP和MySQL的CentOS 7.6上安装Nginx(LEMP堆栈)

本教程说明如何在支持PHP支持(使用PHP-FPM)和MySQL(MariaDB)的CentOS 7服务器上安装Nginx。

什么是LEMP

Nginx的 (发音为“ engine x”)是一个免费的,开源的高性能HTTP服务器。 Nginx以其稳定性,丰富的功能集,简单的配置和低资源消耗而著称。

LEMP先决条件

对于本教程,请使用主机名server1.example.com和IP地址192.168.1.100。这些设置可能因用户而异,因此您可能需要根据需要替换它们。

在本教程中,您将使用nano编辑器来编辑配置文件。 Nano可以通过这种方式安装。

yum -y install nano

我们建议您安装防火墙。如果尚未安装firewalld,并且想使用防火墙,请使用以下命令进行安装:

yum -y install firewalld

启动防火墙,并使其在启动时启动。

systemctl start firewalld.servicesystemctl enable firewalld.service

然后打开SSH端口,并确保可以SSH到服务器。

firewall-cmd --permanent --zone=public --add-service=sshfirewall-cmd --reload

启用其他CentOS资料库

最新的Nginx无法从官方CentOS存储库中获得,因此请包括Nginx项目存储库以进行安装。

nano /etc/yum.repos.d/nginx.repo
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1

安装MySQL(MariaDB)

首先,安装MariaDB作为MySQL的替代方案。 MariaDB是MySQL的免费分支。通过在Shell中运行以下命令来安装MariaDB数据库服务器。

yum -y install mariadb mariadb-server net-tools

然后创建一个MariaDB系统启动链接(以便它在每次系统启动时自动启动)并启动MariaDB服务器。

systemctl enable mariadb.servicesystemctl start mariadb.service

然后确保网络已启用。请注意,MraiDB服务被称为mysql,因为它是兼容的数据库服务器。跑

netstat -tap | grep mysql

它将以以下方式显示。

[[email protected] ~]# netstat -tap | grep mysqltcp 0 0 0.0.0.0:mysql 0.0.0.0:* LISTEN 19842/mysqld 

跑:

mysql_secure_installation

为root用户设置密码(否则任何人都可以访问MySQL数据库!):

[[email protected] ~]# mysql_secure_installation/usr/bin/mysql_secure_installation: line 379: find_mysql_client: command not found
NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDBSERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!
In order to log into MariaDB to secure it, we'll need the currentpassword for the root user. If you've just installed MariaDB, andyou haven't set the root password yet, the password will be blank,so you should just press enter here.
Enter current password for root (enter for none):OK, successfully used password, moving on...
Setting the root password ensures that nobody can log into the MariaDBroot user without the proper authorisation.
Set root password? [Y/n] <-- ENTERNew password: <-- yourrootsqlpasswordRe-enter new password: <-- yourrootsqlpasswordPassword updated successfully!Reloading privilege tables..... Success!
By default, a MariaDB installation has an anonymous user, allowing anyoneto log into MariaDB without having to have a user account created forthem. This is intended only for testing, and to make the installationgo a bit smoother. You should remove them before moving into aproduction environment.
Remove anonymous users? [Y/n] <-- ENTER... Success!
Normally, root should only be allowed to connect from 'localhost'. Thisensures that someone cannot guess at the root password from the network.
Disallow root login remotely? [Y/n] <-- ENTER... Success!
By default, MariaDB comes with a database named 'test' that anyone canaccess. This is also intended only for testing, and should be removedbefore moving into a production environment.
Remove test database and access to it? [Y/n] <-- ENTER- Dropping test database...... Success!- Removing privileges on test database...... Success!
Reloading the privilege tables will ensure that all changes made so farwill take effect immediately.
Reload privilege tables now? [Y/n] <-- ENTER... Success!
Cleaning up...
All done! If you've completed all of the above steps, your MariaDBinstallation should now be secure.
Thanks for using MariaDB![[email protected] ~]#

[[email protected] 〜]#Mysql_secure_installation

安装Nginx

Nginx是nginx.org的软件包,可以按以下方式安装。

yum -y install nginx

接下来,创建并启动nginx系统启动链接。

systemctl enable nginx.servicesystemctl start nginx.service

您可能会收到一个错误消息,说明端口80已在使用中。错误消息如下所示:

[[email protected] ~]# service nginx startStarting nginx: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)nginx: [emerg] still could not bind()                                                           [FAILED][[email protected]erver1 ~]#

这意味着该服务器上已经在运行另一个Web服务器(可能是Apache)。停止Apache服务,然后启动NGINX服务。

systemctl stop httpd.serviceyum remove httpdsystemctl disable httpd.service

然后尝试再次启动Nginx。

systemctl start nginx.service

在防火墙中打开HTTP和HTTPS端口

firewall-cmd --permanent --zone=public --add-service=httpfirewall-cmd --permanent --zone=public --add-service=httpsfirewall-cmd --reload

Shell的结果输出如下所示:

[[email protected] ~]# firewall-cmd --permanent --zone=public --add-service=httpsuccess[[email protected] ~]# firewall-cmd --permanent --zone=public --add-service=httpssuccess[[email protected] ~]# firewall-cmd --reloadsuccess[[email protected] ~]#

在浏览器中输入Web服务器的IP地址或主机名(例如http://192.168.1.100),将显示Nginx欢迎页面。

广告

PHP安装

您可以使PHP 5与Nginx一起使用 PHP-FPM (FastCGI流程管理器)。 PHP-FPM是PHP FastCGI的替代实现,具有一些附加功能,这些功能对各种规模的站点(尤其是那些使用率很高的站点)很有用。您可以使用一些PHP5模块(例如php-cli和php-mysql)安装php-fpm,当通过PHP脚本使用MySQL时需要这些模块,如下所示:

yum -y install php-fpm php-cli php-mysql php-gd php-ldap php-odbc php-pdo php-pecl-memcache php-pear php-mbstring php-xml php-xmlrpc php-mbstring php-snmp php-soap

APC是一个免费且开放的PHP操作码收银员,用于缓存和优化PHP中间代码。它类似于其他PHP操作码缓存,例如eAccelerator和Xcache。强烈建议您安装其中之一以加快PHP页面的速度。

从PHP pecl存储库安装APC。 PECL要求安装Centos开发工具才能编译APC软件包。

yum -y install php-develyum -y groupinstall 'Development Tools'

安装APC。

pecl install apc
[[email protected] ~]# pecl install apcdownloading APC-3.1.13.tgz ...Starting to download APC-3.1.13.tgz (171,591 bytes).................done: 171,591 bytes55 source files, buildingrunning: phpizeConfiguring for:PHP Api Version: 20100412Zend Module Api No: 20100525Zend Extension Api No: 220100525Enable internal debugging in APC [no] : <-- ENTEREnable per request file info about files used from the APC cache [no] : <-- ENTEREnable spin locks (EXPERIMENTAL) [no] : <-- ENTEREnable memory protection (EXPERIMENTAL) [no] : <-- ENTEREnable pthread mutexes (default) [no] : <-- ENTEREnable pthread read/write locks (EXPERIMENTAL) [yes] : <-- ENTERbuilding in /var/tmp/pear-build-rootVrjsuq/APC-3.1.13......

然后打开/etc/php.ini并设置cgi.fix_pathinfo = 0。

nano /etc/php.ini
[...]
; cgi.fix_pathinfo provides *real* PATH_INFO/PATH_TRANSLATED support for CGI.  PHP's
; previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok
; what PATH_INFO is.  For more information on PATH_INFO, see the cgi specs.  Setting
; this to 1 will cause PHP CGI to fix its paths to conform to the spec.  A setting
; of zero causes PHP to behave as before.  Default is 1.  You should fix your scripts
; to use SCRIPT_FILENAME rather than PATH_TRANSLATED.
; http://www.php.net/manual/en/ini.core.php#ini.cgi.fix-pathinfo
cgi.fix_pathinfo=0
[...]

(请阅读 http://wiki.nginx.org/陷阱 找出为什么需要这样做。

添加以下行。

[...]
extension=apc.so

在/etc/php.ini文件的末尾。

此外,为避免时区错误,例如

[28-June-2016 14:21:01] PHP Warning: phpinfo(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Europe/Berlin' for 'CEST/2.0/DST' instead in /usr/share/nginx/html/info.php on line 2

...在/var/log/php-fpm/www-error.log中,当在浏览器中调用PHP脚本时,您需要在/etc/php.ini中设置date.timezone:

[...]
[Date]
; Defines the default timezone used by the date functions
; http://www.php.net/manual/en/datetime.configuration.php#ini.date.timezone
date.timezone = "Europe/Berlin"
[...]

您可以通过运行以下命令来检查系统的正确时区:

猫/ etc / sysconfig /时钟

[[email protected] nginx]#Cat / etc / sysconfig / clockZONE =“欧洲/柏林”[[email protected] nginx]#

接下来,创建并启动php-fpm系统启动链接。

systemctl enable php-fpm.servicesystemctl start php-fpm.service

PHP-FPM是一个守护进程(使用初始化脚本/etc/init.d/php-fpm),该进程在端口9000上运行FastCGI服务器。

Nginx配置

Nginx配置位于/etc/nginx/nginx.conf中,并在此处打开:

nano /etc/nginx/nginx.conf

首先(可选),您可以增加工作进程的数量,并将keepalive_timeout设置为适当的值。

[...]
worker_processes  4;
[...]
    keepalive_timeout  2;
[...]

虚拟主机在/etc/nginx/conf.d目录中的server {}容器中定义。让我们如下更改默认虚拟主机(在/etc/nginx/conf.d/default.conf中):

nano /etc/nginx/conf.d/default.conf
[...]
server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/log/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm index.php;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ .php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #

    location ~ .php$ {
        root           /usr/share/nginx/html;
        try_files $uri =404;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
	
	# deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /.ht {
        deny  all;
    }
}

服务器名称_;将其设置为默认的全包虚拟主机(当然,您也可以在此处指定主机名,例如www.example.com)。

在位置/部分,我将index.php添加到了索引行。根目录/ usr / share / nginx / html;表示文档根目录是目录/ usr / share / nginx / html。

PHP的重要部分是位置〜 .php $ {}节。取消注释并启用。将根目录行更改为您网站的文档根目录(例如,root / usr / share / nginx / html;)。注意,我添加了try_files $ uri = 404;行。防止零日攻击 http://wiki.nginx.org/Pitfalls#Passing_Uncontrol_Requests_to_PHPhttp://forum.nginx.org/read.php?2,88845,page=3)。将fastcgi_param行更改为fastcgi_param SCRIPT_FILENAME $ document_root $ fastcgi_script_name。否则,PHP解释器将无法在浏览器中找到要调用的PHP脚本($ document_root将被转换为/ usr / share / nginx / html,因为它被设置为文档根目录)。

默认情况下,PHP-FPM在端口7.0的127.0.0.1上进行侦听,因此告诉Nginx使用fastcgi_pass 127.0.0.1:9000;行连接到127.0.0.1:9000。您也可以将Unix套接字与PHP-FPM一起使用。这将在第7章中讨论。

保存文件并重新加载Nginx。

systemctl restart nginx.service

然后在文档根目录/ usr / share / nginx / html中创建以下PHP文件...

nano /usr/share/nginx/html/info.php

然后在浏览器中调用该文件(例如http://192.168.1.100/info.php):

来自nginx服务器的PHP信息。

如您所见,PHP 5正在运行,如服务器API行所示,并且正在通过FPM / FastCGI运行。向下滚动以查看PHP5中已启用的所有模块,包括MySQL模块。

MySQL驱动程序已使用PHP激活。

强制PHP-FPM使用Unix套接字

默认情况下,PHP-FPM正在127.0.0.1的端口9000上进行侦听。 PHP-FPM可以使用避免TCP开销的Unix套接字。为此,请打开/etc/php-fpm.d/www.conf ...

nano /etc/php-fpm.d/www.conf

...并使侦听线如下所示:

[...]
;listen = 127.0.0.1:9000
listen = /var/run/php-fpm/php5-fpm.sock
[...]

然后重新加载PHP-FPM:广告

systemctl restart php-fpm.service

然后运行Nginx配置和所有虚拟主机,并更改fastcgi_pass 127.0.0.1:9000行。 fastcgi_pass Unix:/tmp/php5-fpm.sock;例如:

vi /etc/nginx/conf.d/default.conf
[...]
    location ~ .php$ {
        root           /usr/share/nginx/html;
        try_files $uri =404;
        fastcgi_pass   unix:/var/run/php-fpm/php5-fpm.sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
[...]

最后,重新加载Nginx。

systemctl restart nginx.service

将此CentOS 7服务器下载为虚拟机

该设置可以ova / ovf格式(与VMWare和Virtualbox兼容)作为虚拟机下载提供给howtoforge订户。

VM登录详细信息

  • 根密码为:如何锻造
  • “管理员”用户的密码为:如何锻造

请在首次登录时更改两个密码。

  • 虚拟机的IP地址为192.168.1.100。
Sidebar