Ubuntu LNMP环境中Nginx配置指南
在Ubuntu上安装Nginx需通过APT包管理器完成,命令如下:
sudo apt update && sudo apt install nginx -y
安装完成后,可通过sudo systemctl status nginx检查服务状态,或浏览器访问服务器IP验证默认页面是否显示。
服务器块(Server Block)是Nginx实现虚拟主机的核心机制,相当于Apache的VirtualHost,用于处理不同域名的请求。
Nginx的站点配置文件建议存放在/etc/nginx/sites-available/目录(便于管理),通过符号链接到/etc/nginx/sites-enabled/目录启用。
sudo nano /etc/nginx/sites-available/yourdomain.com
在配置文件中添加以下内容(需根据实际情况修改):
server {
listen 80; # 监听HTTP端口(默认80)
server_name yourdomain.com www.yourdomain.com; # 域名列表(支持多域名)
root /var/www/yourdomain.com; # 网站根目录(需手动创建)
index index.php index.html index.htm; # 默认首页文件顺序
# 处理静态资源请求
location / {
try_files $uri $uri/ =404; # 尝试查找文件,不存在则返回404
}
# 处理PHP请求(关键:连接PHP-FPM)
location ~ \.php$ {
include snippets/fastcgi-php.conf; # 引入FastCGI配置片段
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # PHP-FPM socket路径(需与版本匹配)
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; # 传递脚本路径
include fastcgi_params; # 引入FastCGI通用参数
}
# 禁止访问.htaccess等隐藏文件(Apache遗留配置)
location ~ /\.ht {
deny all;
}
}
创建符号链接以启用配置:
sudo ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/
sudo mkdir -p /var/www/yourdomain.com # 创建根目录
sudo chown -R www-data:www-data /var/www/yourdomain.com # 设置所有者(Nginx默认用户)
sudo chmod -R 755 /var/www/yourdomain.com # 设置目录权限
LNMP中的PHP处理依赖PHP-FPM(FastCGI进程管理器),需确保其与Nginx配置一致。
编辑PHP-FPM池配置文件(以Ubuntu默认路径为例):
sudo nano /etc/php/7.4/fpm/pool.d/www.conf
找到user和group行,修改为:
user = www-data
group = www-data
保存后重启PHP-FPM:
sudo systemctl restart php7.4-fpm
在重载前务必检查配置文件语法,避免因错误导致服务中断:
sudo nginx -t
若输出nginx: configuration file /etc/nginx/nginx.conf test is successful则表示配置正确。
sudo systemctl reload nginx
若使用UFW(Ubuntu默认防火墙),需允许HTTP(80)和HTTPS(443)流量:
sudo ufw allow 'Nginx Full' # 允许HTTP和HTTPS
sudo ufw enable # 启用防火墙(若未启用)
为提升安全性,建议为网站配置免费SSL证书(Let’s Encrypt):
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
按提示完成证书申请,Certbot会自动修改Nginx配置以支持HTTPS(默认监听443端口)。
创建PHP测试文件以验证PHP解析是否正常:
sudo nano /var/www/yourdomain.com/info.php
添加以下内容:
<?php phpinfo(); ?>
保存后在浏览器访问http://yourdomain.com/info.php,若显示PHP信息页面则表示配置成功。
listen:指定监听端口(80为HTTP,443为HTTPS)。server_name:域名列表,支持多域名(如server_name example.com www.example.com;)。root:网站根目录,需与创建的目录一致。fastcgi_pass:PHP-FPM的socket路径(需与/etc/php/7.x/fpm/pool.d/www.conf中的listen一致)。try_files:静态资源处理指令,优先查找文件,不存在则返回404。通过以上步骤,即可在Ubuntu LNMP环境中完成Nginx的基本配置,支持静态资源、PHP动态内容的处理及多域名虚拟主机部署。