Install LEMP stack(Linux Nginx MySQL PHP)on CentOS7
step one — install nginx
- 添加 CentOS 7 EPEL repository
sudo yum install epel-release
- 安装 nginx
sudo yum install nginx
- 启动 nginx
sudo systemctl start nginx
- 访问 http://your_ip 如果出现nginx 的默认欢迎页面则安装成功。如果提示无法访问,可以做如下尝试
- 在 server 上 执行 curl http://127.0.0.1 如果成功返回了 nginx 的默认欢迎页面的内容,则可以断定是 防火墙问题。这时候可以选择关闭防火墙(不推荐)或者开放 80 端口。
- 开放 80 端口。
- 添加防火墙规则:
sudo firewall-cmd --permanent --zone=public --add-port=80/tcp # http协议基于TCP传输协议,放行80端口
- 重启防火墙
sudo systemctl restart firewalld
- 添加防火墙规则:
- 设置 nginx 开机自启
sudo systemctl enable nginx
step two — install MySQL (MariaDB)
- 安装 MariaDB
sudo yum install mariadb-server mariadb
- 启动MySQL
sudo systemctl start mariadb
- 执行 安全脚本 做一些初始化操作, 过程中会设置 root 密码,其他选择根据提示操作即可。
sudo mysql_secure_installation
- 设置 MySQL 开机自启。
sudo systemctl enable mariadb
step three — install PHP
- 安装 PHP php-mysql php-fpm
sudo yum install php php-mysql php-fpm
- 配置 php
- root 权限编辑 php.ini 文件
sudo vi /etc/php.ini
找到
;cgi.fix_pathinfo=1
将它改为
cgi.fix_pathinfo=0
然后保存并退出。
- root权限编辑 www.conf 文件
sudo vi /etc/php-fpm.d/www.conf
- 首先将 listen 参数改为
listen = /var/run/php-fpm/php-fpm.sock
- 然后将 listen.owner listen.group 设置为
listen.owner = nginx listen.group = nginx
- 最后将 user group 由 apace 改为 nginx
user = nginx group = nginx
- 首先将 listen 参数改为
- root 权限编辑 php.ini 文件
- 启动 php-fpm
sudo systemctl start php-fpm
- 设置 php-fpm 开机自启
sudo systemctl enable php-fpm
step four — 配置 nginx 处理 PHP 页面
- 编辑 默认的 nginx 的server 配置
sudo vi /etc/nginx/conf.d/default.conf
默认配置如下:
server { listen 80; server_name localhost; location / { root /usr/share/nginx/html; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } }
将其改为:
server { listen 80; server_name server_domain_name_or_IP; # note that these lines are originally from the "location /" block root /usr/share/nginx/html; index index.php index.html index.htm; location / { try_files $uri $uri/ =404; } error_page 404 /404.html; error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } location ~ \.php$ { try_files $uri =404; 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; } }
- 检查 配置文件
nginx -t
- 重启 nginx ,使修改生效。
sudo systemctl restart nginx
备注:
如果找不到 default.conf 文件,说明默认的 server 块配置在 nginx.conf 文件中。直接将 nginx.conf 中的 server 块移除,然后去 conf.d 文件夹下新建一个 .conf 结尾的文件,把修改后的配置填写进去即可。
step five — 测试 PHP文件 处理是否正常
- 在站点根目录下编辑 info.php 文件
sudo vi /usr/share/nginx/html/info.php
- 输入
<?php phpinfo(); ?>
保存并退出编辑器。
- 访问 http://your_ip/info.php, 如果出现了 PHP 相关的信息表格,则说明配置没有问题,PHP 是正常处理。
- 删除 info.php 文件。需要的时候可以重复此步骤创建。
至此,LEMP 已经完成安装。