虽然是很久以前做的了,但是还是记录一下吧,因为五一没学习没东西更新博客了(嘻嘻)

Nginx基础配置与使用指南

Nginx简介

Nginx是一款轻量级的Web服务器和反向代理服务器,以其高性能、稳定性和低资源消耗而闻名。它可以作为HTTP服务器,也可以作为反向代理服务器,支持负载均衡等高级功能。

基本命令

1. 服务管理

1
2
3
4
5
6
7
8
9
10
11
# 启动服务
/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf

# 关闭服务
/usr/local/nginx/sbin/nginx -s stop

# 重启服务
/usr/local/nginx/sbin/nginx -s reload

# 优雅退出
/usr/local/nginx/sbin/nginx -s quit

2. 配置文件管理

1
2
3
4
5
# 编辑主配置文件
vim /usr/local/nginx/conf/nginx.conf

# 查看错误日志
tail -f /usr/local/nginx/logs/error.log

配置详解

1. 基础配置结构

1
2
3
4
5
6
7
8
# 主配置文件
http {
include mime.types;
default_type application/octet-stream;

# 包含其他配置文件
include /usr/local/nginx/conf/conf.d/*.conf;
}

2. 站点配置示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
server {
listen 80;
server_name example.com;

# 网站根目录
root /var/www/html;

# 默认首页
index index.html index.htm;

# 路径配置
location /admin {
root /var/www/admin;
index index.html;
}
}

3. 反向代理配置

1
2
3
4
5
location /api {
proxy_pass http://backend-server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}

常见操作流程

1. 添加新站点

  1. 创建配置文件
1
vim /usr/local/nginx/conf/conf.d/mysite.conf
  1. 编写配置内容
1
2
3
4
5
server {
listen 80;
server_name mysite.com;
root /var/www/mysite;
}
  1. 重新加载配置
1
/usr/local/nginx/sbin/nginx -s reload

2. 故障排查

  1. 检查配置语法
1
/usr/local/nginx/sbin/nginx -t
  1. 查看错误日志
1
tail -f /usr/local/nginx/logs/error.log