Nginx 基础教程:安装、配置与实用指南

491 阅读3分钟

Nginx 入门教程:从安装到基本使用

1. Nginx 是什么?

Nginx 是一款高性能的 HTTP 和反向代理服务器,广泛用于 Web 服务器、负载均衡、缓存等多个场景。凭借其高并发和低内存占用的特性,Nginx 已经成为了许多公司和开发者的首选。

2. 安装 Nginx

在 Linux 系统上安装 Nginx 非常简单,以下是在 Ubuntu 和 CentOS 系统上的安装方式。

Ubuntu:

sudo apt update  
sudo apt install nginx  

CentOS:

sudo yum install epel-release  
sudo yum install nginx  

安装完成后,可以通过以下命令启动 Nginx:

sudo systemctl start nginx  

在浏览器中访问 http://localhost,如果看到 Nginx 欢迎页面,说明安装成功!

3. Nginx 的基本配置

Nginx 的配置文件通常位于 /etc/nginx/nginx.conf。这个配置文件是 Nginx 的主配置文件,可以定义服务器的行为,比如监听的端口、根目录、日志位置等。

以下是配置文件的主要结构:

worker_processes auto;

events {  
    worker_connections 1024;  
}

http {  
    include       mime.types;  
    default_type  application/octet-stream;

    sendfile        on;  
    keepalive_timeout  65;

    server {  
        listen       80;  
        server_name  localhost;

        location / {  
            root   /usr/share/nginx/html;  
            index  index.html index.htm;  
        }

        error_page  500 502 503 504  /50x.html;  
        location = /50x.html {  
            root   /usr/share/nginx/html;  
        }  
    }  
}  

4. 配置一个简单的网站

让我们配置一个简单的静态网站。假设网站文件在 /var/www/my_website 目录下。

  1. 编辑配置文件:

    sudo nano /etc/nginx/sites-available/my_website  
    
  2. 添加以下内容:

    server {  
        listen 80;  
        server_name mywebsite.com;
    
        location / {  
            root /var/www/my_website;  
            index index.html;  
        }  
    }  
    
  3. 启用配置:

    sudo ln -s /etc/nginx/sites-available/my_website /etc/nginx/sites-enabled/  
    
  4. 测试配置是否正确:

    sudo nginx -t  
    
  5. 重新加载 Nginx:

    sudo systemctl reload nginx  
    

现在可以通过 http://mywebsite.com 访问您的网站。

5. 配置反向代理

反向代理是 Nginx 的一个强大功能,用于将请求转发到后台服务器(如 Node.js、Python)。假设我们有一个运行在 localhost:3000 的应用。

server {  
    listen 80;  
    server_name myapp.com;

    location / {  
        proxy_pass http://localhost:3000;  
        proxy_set_header Host $host;  
        proxy_set_header X-Real-IP $remote_addr;  
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  
        proxy_set_header X-Forwarded-Proto $scheme;  
    }  
}  

这样,访问 myapp.com 时,Nginx 会将请求转发到 localhost:3000,实现反向代理。

6. 启用 HTTPS

为网站添加 HTTPS,可以使用 Let's Encrypt 的免费 SSL 证书。首先安装 Certbot,然后使用 Certbot 为您的域名生成 SSL 证书:

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

按照提示完成操作后,Certbot 会自动为 Nginx 配置 SSL 证书。到此,您就可以通过 HTTPS 安全访问网站了。

7. 常见的 Nginx 命令

  • 启动 Nginxsudo systemctl start nginx
  • 停止 Nginxsudo systemctl stop nginx
  • 重启 Nginxsudo systemctl restart nginx
  • 重新加载配置sudo systemctl reload nginx
  • 测试配置文件sudo nginx -t

总结

Nginx 是一个强大而灵活的 Web 服务器和反向代理服务器。本文从安装、基础配置到反向代理和 HTTPS 配置等多方面介绍了 Nginx 的基本用法,帮助您快速上手使用 Nginx 搭建网站。希望对您有所帮助!