在Ubuntu服务器上搭建php环境
操作系统 : Ubuntu Server 20.04 LTS 64bit
安装版本 : php8.0 + nginx/1.18.0 (Ubuntu)
PHP
新增 ondrej源
1
2
3$ sudo add-apt-repository ppa:ondrej/php
$ sudo apt-get update安装 php8.0
1
$ sudo apt install php8.0 -y
查看已安装扩展
1
$ php -m
安装需要的扩展 FastCGI 进程管理器(FPM)
1
$ sudo apt install php8.0-fpm -y
NGINX
安装Nginx
1
$ sudo apt install nginx -y
查看 Nginx 是否启动成功
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18$ sudo systemctl status nginx
● nginx.service - A high performance web server and a reverse proxy server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: active (running) since Tue 2021-09-21 09:00:54 CST; 10s ago
Docs: man:nginx(8)
Process: 16559 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
Process: 16571 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
Main PID: 16572 (nginx)
Tasks: 2 (limit: 2270)
Memory: 2.6M
CGroup: /system.slice/nginx.service
├─16572 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
└─16573 nginx: worker process
Sep 21 09:00:54 VM-8-3-ubuntu systemd[1]: Starting A high performance web server and a reverse proxy server...
Sep 21 09:00:54 VM-8-3-ubuntu systemd[1]: Started A high performance web server and a reverse proxy server.
创建一个新的站点
找到 php-fpm 进程服务扩展配置文件, 在此文件里可以得到有关接收FastCGI请求的地址
1
$ vim /etc/php/8.0/fpm/pool.d/www.conf
/etc/php/8.0/fpm/pool.d/www.conf
1
2
3
4.
.
.
listen = /run/php/php8.0-fpm.sock创建一个网站目录
1
$ sudo mkdir -p /var/www/example.com/public
给网站目录配置相应的权限
1
$ sudo chown -R $USER:$USER /var/www/example.com/public
在网站根目录下增加一个入口文件
1
$ sudo vim /var/www/example.com/public/index.php
在其中, 添加以下示例php:
/var/www/example.com/public/index.php
1
2
phpinfo();接下来我们为 Nginx 来创建一个服务器块. 与直接修改默认配置文件不同, 我们在以下位置创建一个新文件:
1
sudo vim /etc/nginx/sites-available/example.com
粘贴到以下内容添加到文件中.
/etc/nginx/sites-available/example.com
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19server {
listen 81;
listen [::]:81;
server_name example.com;
root /var/www/example.com/public;
index index.html index.htm index.php;
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
location ~ \.php$ {
try_files $uri =404;
include fastcgi.conf;
fastcgi_pass unix:/run/php/php8.0-fpm.sock;
}
}在这里我使用了 81 端口的原因是因为在同目录下的 default 文件有一个默认配置块, 这里我们为了减少操作流程直接使用81端口.
接下来, 让我们通过在sites-enabled目录新建一个链接, 好让 Nginx 在启动过程中会读取这个目录:
1
$ sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
为避免可能由于添加其他服务器名称而引起的哈希存储区内存问题, 有必要调整/etc/nginx/nginx.conf文件中的单个值.
1
$ sudo vim /etc/nginx/nginx.conf
找到 server_names_hash_bucket_size 指令并删除#符号:
/etc/nginx/nginx.conf
1
2
3
4.
.
.
server_names_hash_bucket_size 64;接下来,测试以确保我们在 Nginx 文件中的改动,没有任何问题:
1
$ sudo nginx -t
确认没有问题之后就可以重启我们的 nginx 载入新加入的配置
1
$ sudo systemctl restart nginx
最后访问我们的 http://localhost:81 就应该能看到 phpinfo() 输出的页面了