sudo apt update
sudo apt install nginx
安装完成后,Nginx 会自动启动。可以通过以下命令检查状态:
sudo systemctl status nginx
在浏览器中访问服务器的 IP 地址或域名,应该能看到 Nginx 的欢迎页面。
Nginx 的主要配置文件位于:
/etc/nginx/nginx.conf
站点特定的配置文件通常放在:
/etc/nginx/sites-available/
然后通过符号链接到:
/etc/nginx/sites-enabled/
sudo nano /etc/nginx/sites-available/example.com
示例配置内容:
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
sudo systemctl start nginxsudo systemctl stop nginxsudo systemctl restart nginxsudo systemctl reload nginxsudo systemctl enable nginxsudo systemctl disable nginxsudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.com
upstream backend {
server backend1.example.com;
server backend2.example.com;
server backend3.example.com;
}
server {
location / {
proxy_pass http://backend;
}
}
proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m inactive=60m;
server {
location / {
proxy_cache my_cache;
proxy_pass http://backend;
}
}
/var/log/nginx/access.log/var/log/nginx/error.log可以通过 tail -f 命令实时查看日志:
sudo tail -f /var/log/nginx/access.log
sudo tail -f /var/log/nginx/error.log
如果遇到端口冲突错误,可以: - 修改 Nginx 监听端口 - 停止占用端口的服务
确保 Nginx 用户(通常是 www-data)有访问网站文件的权限:
sudo chown -R www-data:www-data /var/www/example.com
sudo chmod -R 755 /var/www/example.com
使用 nginx -t 测试配置,根据错误信息修正配置问题。
希望这个指南能帮助您在 Ubuntu 上成功安装和配置 Nginx!如需更高级的配置,可以参考 Nginx 官方文档。