在LNMP(Linux, Nginx, MySQL, PHP)环境下配置Nginx主要涉及以下几个步骤:
首先,确保你的系统已经安装了Nginx。你可以使用包管理器来安装:
sudo apt update
sudo apt install nginx
Nginx的配置文件通常位于 /etc/nginx/nginx.conf
,但更常见的是在 /etc/nginx/sites-available/
目录下创建虚拟主机配置文件。
假设你要为你的网站 example.com
创建一个虚拟主机配置文件:
sudo nano /etc/nginx/sites-available/example.com
在文件中添加以下内容:
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 根据你的PHP版本调整
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
}
创建一个符号链接以启用该配置:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
在重新加载Nginx之前,测试配置文件是否有语法错误:
sudo nginx -t
如果一切正常,你会看到类似以下的输出:
nginx: configuration file /etc/nginx/nginx.conf test is successful
重新加载Nginx以应用新的配置:
sudo systemctl reload nginx
确保PHP-FPM已经安装并运行:
sudo apt install php7.4-fpm
编辑PHP-FPM配置文件 /etc/php/7.4/fpm/pool.d/www.conf
,确保以下行没有被注释:
listen = /var/run/php/php7.4-fpm.sock
然后重启PHP-FPM服务:
sudo systemctl restart php7.4-fpm
确保MySQL已经安装并运行:
sudo apt install mysql-server
运行安全脚本以设置MySQL的安全选项:
sudo mysql_secure_installation
按照提示完成设置。
如果你使用的是UFW(Uncomplicated Firewall),确保允许HTTP和HTTPS流量:
sudo ufw allow 'Nginx Full'
打开浏览器并访问 http://example.com
,你应该能够看到你的网站。
通过以上步骤,你就可以在LNMP环境下成功配置Nginx了。如果有任何问题,请检查Nginx的错误日志 /var/log/nginx/error.log
以获取更多信息。