Ubuntu LNMP中Nginx如何配置
Ubuntu LNMP环境中Nginx配置指南
1. 安装Nginx
在Ubuntu上安装Nginx需通过APT包管理器完成,命令如下:
sudo apt update &
&
sudo apt install nginx -y
安装完成后,可通过sudo systemctl status nginx
检查服务状态,或浏览器访问服务器IP验证默认页面是否显示。
2. 配置Nginx服务器块(虚拟主机)
服务器块(Server Block)是Nginx实现虚拟主机的核心机制,相当于Apache的VirtualHost,用于处理不同域名的请求。
2.1 创建服务器块配置文件
Nginx的站点配置文件建议存放在/etc/nginx/sites-available/
目录(便于管理),通过符号链接到/etc/nginx/sites-enabled/
目录启用。
sudo nano /etc/nginx/sites-available/yourdomain.com
2.2 基础配置模板
在配置文件中添加以下内容(需根据实际情况修改):
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;
}
}
2.3 启用服务器块
创建符号链接以启用配置:
sudo ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/
2.4 创建网站目录并设置权限
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 # 设置目录权限
3. 配置PHP-FPM兼容性
LNMP中的PHP处理依赖PHP-FPM(FastCGI进程管理器),需确保其与Nginx配置一致。
3.1 修改PHP-FPM用户/组
编辑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
4. 测试与重载Nginx配置
4.1 语法检查
在重载前务必检查配置文件语法,避免因错误导致服务中断:
sudo nginx -t
若输出nginx: configuration file /etc/nginx/nginx.conf test is successful
则表示配置正确。
4.2 重载配置
sudo systemctl reload nginx
5. 配置防火墙
若使用UFW(Ubuntu默认防火墙),需允许HTTP(80)和HTTPS(443)流量:
sudo ufw allow 'Nginx Full' # 允许HTTP和HTTPS
sudo ufw enable # 启用防火墙(若未启用)
6. 可选:配置SSL证书(HTTPS)
为提升安全性,建议为网站配置免费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端口)。
7. 验证配置
创建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动态内容的处理及多域名虚拟主机部署。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: Ubuntu LNMP中Nginx如何配置
本文地址: https://pptw.com/jishu/730519.html