🌈个人主页:前端青山
🔥系列专栏:Nginx篇
🔖人终将被年少不可得之物困其一生
依旧青山,本期给大家带来Nginx篇专栏内容:Nginx-使用指南
前言
大家好,我是青山。Nginx 是一个高性能的 HTTP 和反向代理服务器,广泛应用于各种 Web 应用和服务中。本文将详细介绍 Nginx 的安装、启动、配置、常用命令、高级功能以及常见问题解决方法,帮助你更好地理解和使用 Nginx。
目录
1. 安装 Nginx
1.1 在 Ubuntu 上安装
sudo apt update sudo apt install nginx
1.2 在 CentOS 上安装
sudo yum install epel-release sudo yum install nginx
1.3 在 Debian 上安装
sudo apt update sudo apt install nginx
1.4 在 macOS 上安装
使用 Homebrew 安装 Nginx:
brew install nginx
2. 启动、停止和重启 Nginx
2.1 启动 Nginx
sudo systemctl start nginx
2.2 停止 Nginx
sudo systemctl reload nginx
sudo systemctl stop nginx
2.3 重启 Nginx
sudo systemctl restart nginx
2.4 重新加载配置文件
2.5 检查 Nginx 状态
sudo systemctl status nginx
3. 配置 Nginx
3.1 配置文件位置
Nginx 的主配置文件通常位于 /etc/nginx/nginx.conf
。每个虚拟主机的配置文件通常位于 /etc/nginx/sites-available/
目录下,并通过符号链接链接到 /etc/nginx/sites-enabled/
目录。
3.2 主配置文件结构
user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; } http { sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; gzip on; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; }
3.3 虚拟主机配置示例
以下是一个简单的 Nginx 虚拟主机配置示例:
server { listen 80; server_name example.com; root /var/www/example.com; index index.html index.htm; location / { try_files $uri $uri/ =404; } location /api/ { 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; } }
3.4 解释
listen 80;
:监听 80 端口。server_name example.com;
:指定服务器名称。root /var/www/example.com;
:指定网站根目录。index index.html index.htm;
:指定默认索引文件。location / { ... }
:处理根路径的请求。location /api/ {