插件窝 干货文章 Ubuntu中Nginx怎么安装与配置

Ubuntu中Nginx怎么安装与配置

Nginx 配置 sudo example 595    来源:    2025-04-25

Ubuntu 中 Nginx 的安装与配置指南

安装 Nginx

1. 更新软件包列表

sudo apt update

2. 安装 Nginx

sudo apt install nginx

3. 验证安装

安装完成后,Nginx 会自动启动。可以通过以下命令检查状态:

sudo systemctl status nginx

4. 访问默认页面

在浏览器中访问服务器的 IP 地址或域名,应该能看到 Nginx 的欢迎页面。

基本配置

1. 主要配置文件

Nginx 的主要配置文件位于:

/etc/nginx/nginx.conf

2. 站点配置文件

站点特定的配置文件通常放在:

/etc/nginx/sites-available/

然后通过符号链接到:

/etc/nginx/sites-enabled/

3. 创建新站点配置

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;
    }
}

4. 启用站点

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

5. 测试配置

sudo nginx -t

6. 重启 Nginx

sudo systemctl restart nginx

常用命令

  • 启动 Nginx:sudo systemctl start nginx
  • 停止 Nginx:sudo systemctl stop nginx
  • 重启 Nginx:sudo systemctl restart nginx
  • 重新加载配置(不中断服务):sudo systemctl reload nginx
  • 设置开机启动:sudo systemctl enable nginx
  • 禁用开机启动:sudo systemctl disable nginx

进阶配置

1. 启用 HTTPS (使用 Let's Encrypt)

sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.com

2. 配置负载均衡

upstream backend {
    server backend1.example.com;
    server backend2.example.com;
    server backend3.example.com;
}

server {
    location / {
        proxy_pass http://backend;
    }
}

3. 配置缓存

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

常见问题解决

1. 端口冲突

如果遇到端口冲突错误,可以: - 修改 Nginx 监听端口 - 停止占用端口的服务

2. 权限问题

确保 Nginx 用户(通常是 www-data)有访问网站文件的权限:

sudo chown -R www-data:www-data /var/www/example.com
sudo chmod -R 755 /var/www/example.com

3. 配置测试失败

使用 nginx -t 测试配置,根据错误信息修正配置问题。

希望这个指南能帮助您在 Ubuntu 上成功安装和配置 Nginx!如需更高级的配置,可以参考 Nginx 官方文档。