centos搭建LNMP服务器

  • 我们首先来看一张图片:Fuck DDOS
  • 前天折腾完apache,顺便装好了MySQL和PHP,放了一个Discuz!的开源论坛程序,什么乱七八糟权限都没管,全是弱密码。刚准备写个博纪念一下,发现我VPS被人黑了……无奈只好重新安装一遍centos。在vagarlee的建议下,我吸取上一次的教训,使用更轻量的Nginx来替代Apache。 ### 安装Nginx 在使用yum安装Nginx的时候有一些小小的麻烦,需要自己建立一个nginx.repo的软件源配置文件。
    1
    vim /etc/yum.repo.d/nginx.repo

在其中填写如下内容:

1
2
3
4
5
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1

保存,使用

1
yum -y install nginx

nginx安装完成。
启动Nginx服务:

1
/etc/init.d/nginx start

这个时候访问VPS的IP地址应该就能出现Nginx的欢迎页面了。 ### 安装MySQL

1
yum install mysql-server mysql mysql-deve

我第一次安装MySQl的时候想当然只安装了mysql,并没有安装mysql-server导致数据库无法使用,mysql-server是一个服务端,需要安装。
启用MySQl服务:

1
service mysqld start

这时候会出现长长的提示信息,恭喜数据库安装成功。
接下来我们给数据库设置管理员账号和密码:

1
mysqladmin -u root password 'yourpassword'

安装PHP

这一步比较简单,直接使用yum:

1
yum install php-fpm php-mysql

  • 至此,LNMP环境的软件包已经全部安装完成,下面就是简单的配置阶段。

配置PHP

更改下面的文件:

1
vim /etc/php.ini

将1改为0

1
cgi.fix_pathinfo = 0

这儿有一段英文解释,来自digitalocean: >If this number is kept as a 1, the php interpreter will do its best to process the file that is as near to the requested file as possible. This is a possible security risk. If this number is set to 0, conversely, the interpreter will only process the exact file path—a much safer alternative.

配置Nginx

主要是改一下Nginx.conf这个文件夹里的配置文件:

1
vim /etc/nginx/conf.d/default.conf

改成了这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}

  • server_name后面的地址为localhost
  • location中的root地址为/usr/share/nginx/html
  • 在index index.html index.htm后加上index.php
  • "location ~ \.php$ {",前的注释去了,改fastcgi_param后面的内容为SCRIPT_FILENAME $document_root

保存退出后打开php-fpm的配置:

1
vim /etc/php-fpm.d/www.conf

找到

1
2
3
4
5
6
7
; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
; will be used.
; RPM: apache Choosed to be able to access some dir as httpd
user = nginx
; RPM: Keep a group allowed to write in log dir.
group = nginx

改成User=nginxgroup=nginx 重新启动php-fpm即可 ### 参考的文档 Nginx官方文档
Installing Nginx and php-fpm - Setup For Nginx
Nginx -PHP FastCGI Example