CentOS 7安装配置LEMP(Nginx PHP FastCGI MariaDB)

系统配置

确保你的系统为最新版本:

  1. yum update

从EPEL安装Nginx

最快最容易安装Nginx的方式是使用第三方源EPEL

  1. sudo yum install epel-release
  2. yum update
  3. yum install nginx

这些命令指安装EPEL仓库,拉取最新的metadata,之后安装Nginx

配置Nginx

systemd启动Nginx

Nginx安装完成后,需要在systemd激活和启动,可以使用systemctl命令来做

  1. systemctl enable nginx.service
  2. systemctl start nginx.service

然后你可以检查其状态确保nginx始终启动

  1. systemctl status nginx.service

配置Nginx虚拟主机

一旦nginx安装完成,你需要在配置文件配置server块。每个server块需要一个server和location指令。你可以把server块分别建立不同文件,或者直接放到一个文件/etc/nginx/nginx.conf。在这个例子里,我们使用多个配置文件。默认地,Nginx会引用/etc/nginx/conf.d目录下的.conf文件
/etc/nginx/conf.d/example.com.conf:

  1. server {
  2. listen  80;
  3. server_name www.example.com example.com;
  4. access_log /var/www/example.com/logs/access.log;
  5. error_log /var/www/example.com/logs/error.log;
  6.     
  7. location / {
  8.     root  /var/www/example.com/public_html;
  9.     index index.html index.htm index.php;
  10.     }
  11. }

你想托管额外的网站时,可以把配置文件放在/etc/nginx/conf.d目录。一旦建立好配置文件,你需要为你的public html文件,日志目录创建目录:

  1. mkdir -p /var/www/example.com/{public_html,logs}

配置文件虚拟主机后,需要重启nginx以生效配置

  1. systemctl restart nginx.service

部署PHP FastCGI

如果你的网站是PHP写的,你需要实现PHP-FastCGI以便能让Nginx能正确地处理和解析PHP代码。你可以从EPEL仓库使用YUM安装

  1. yum install php-cli php spawn-fcgi

PHP-FastCGI安装好后,需要创建一个用来启动和控制php-cgi进程的脚本。
/usr/bin/php-fastcgi:

  1. #!/bin/sh
  2. if [ `grep -c "nginx" /etc/passwd` = "1" ]; then
  3.     FASTCGI_USER=nginx
  4. elif [ `grep -c "www-data" /etc/passwd` = "1" ]; then
  5.     FASTCGI_USER=www-data
  6. elif [ `grep -c "http" /etc/passwd` = "1" ]; then
  7.     FASTCGI_USER=http
  8. else
  9. # Set the FASTCGI_USER variable below to the user that
  10. # you want to run the php-fastcgi processes as
  11.  
  12. FASTCGI_USER=
  13. fi
  14.  
  15. /usr/bin/spawn-fcgi -a 127.0.0.1 -p 9000 -C 6 -u $FASTCGI_USER -f /usr/bin/php-cgi

脚本创建好后,设置其有执行权限

  1. chmod +x /usr/bin/php-fastcgi

把PHP-FastCGI配置为服务

PHP-FastCGI安装好后,它不会自动地在systemd注册为服务。如果你想用systemd更方便地管理PHP-FastCGI,可以把它配置为systemd服务。需要创建一个服务文件指向/usr/bin/php-fastcgi:
/etc/systemd/system/php-fastcgi.service:

  1. [Unit]
  2. Description=php-fastcgi systemd service script
  3.  
  4. [Service]
  5. Type=forking
  6. ExecStart=/usr/bin/php-fastcgi start
  7.  
  8. [Install]
  9. WantedBy=multi-user.target

服务文件创建好后,需要重载systemd守护进程以激活此服务,然后启动它。

  1. systemctl daemon-reload
  2. systemctl enable php-fastcgi.service
  3. systemctl start php-fastcgi.service

安装MariaDB

CentOS 7官方源已经没有MySQL了,已经用MariaDB替代,不过放心,这个是完全兼容MySQL的,用法一样。
1.从官方源安装MariaDB

  1. yum install mariadb-server

2.安装完成后,使用systemctl来激活并启动mariadb

  1. systemctl enable mariadb.service
  2. systemctl start mariadb.service

3.使用mysql_secure_installation命令来加固MariaDB

  1. mysql_secure_installation

到此LEMP安装完成。