在Ubuntu上搭建LAMP(Linux、Apache、MySQL和PHP)开发环境是一个相对直接的过程。以下是详细的步骤:
首先,打开终端并输入以下命令来安装Apache:
sudo apt update
sudo apt install apache2
安装完成后,你可以通过在浏览器中输入 http://localhost
来验证Apache是否成功安装。如果显示了“It works!”的消息,那么Apache就已经正常运行了。
接下来,安装MySQL服务器:
sudo apt install mysql-server
在安装过程中,系统会提示你设置MySQL的root用户密码,请务必设置一个强密码并妥善保管。
然后,安装PHP及其常用模块:
sudo apt install php php-cli php-fpm php-mysql php-curl php-gd php-mbstring php-xml php-zip
如果你打算使用PHP-FPM来处理PHP请求,你还需要进行一些额外的配置。
启动PHP-FPM服务:
sudo systemctl start php7.4-fpm
设置PHP-FPM开机自启:
sudo systemctl enable php7.4-fpm
如果你使用Nginx作为Web服务器,你需要修改Nginx配置文件以使用PHP-FPM。通常这个文件位于 /etc/nginx/sites-available/default
或类似的目录下。以下是一个示例配置:
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
index index.php index.html index.htm index.nginx-debian.html;
server_name _;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
}
保存更改后,重启Nginx以应用新的配置:
sudo systemctl restart nginx
创建一个PHP文件来验证PHP是否正确安装和配置。在 /var/www/html
目录下创建一个名为 info.php
的文件,并添加以下内容:
<?php
phpinfo();
?>
保存并退出编辑器,然后在浏览器中访问 http://your_server_ip/info.php
。如果你能看到PHP的详细信息页面,那么PHP就已经成功配置了。
至此,你已经在Ubuntu上成功搭建了一个LAMP开发环境。你可以开始编写和测试你的Web应用程序了。