当前位置:首页 > nginx > 正文

nginx 快速入门

  • nginx
  • 2024-05-05 06:33:37
  • 4631

简介
Nginx(发音为“engine-x”)是一个流行的开放源码 Web 服务器和反向代理,以其高性能、稳定性和可扩展性而闻名。 Nginx 通常用于为网站、应用程序和 API 提供服务。
安装
Nginx 可以通过官方网站或各种 Linux 发行版的包管理器安装。 以下是一些常见的命令:
Ubuntu/Debian:sudo apt-get install nginx
CentOS/Red Hat:sudo yum install nginx
macOS(使用 Homebrew):brew install nginx
基本配置
Nginx 的主要配置文件是 /etc/nginx/nginx.conf。 基本配置如下:
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
server {
listen 80 default_server;
server_name localhost;
location / {
root /usr/share/nginx/html;
}
}
}
user nginx;: Nginx 进程的运行用户。
worker_processes auto;: 自动创建工作进程的数量。
error_log /var/log/nginx/error.log;: 错误日志文件的位置。
worker_connections 1024;: 每个工作进程允许的最大并发连接数。
server { ... }: 虚拟主机块,定义了一个监听端口 80 的服务器。
location / { ... }: 根位置块,定义了当请求根路径(/)时要执行的操作。
启动和停止
启动 Nginx:sudo service nginx start
停止 Nginx:sudo service nginx stop
反向代理
反向代理用于将请求转发到其他服务器。 以下配置将来自端口 80 的所有流量转发到端口 8080 上的另一台服务器:
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://localhost:8080;
}
}
缓存
Nginx 可以通过以下配置启用缓存:
http {
...
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m;
...
server {
...
location / {
...
proxy_cache my_cache;
}
}
}
负载均衡
Nginx 可以通过以下配置用于负载均衡:
http {
...
upstream my_upstream {
server server1.example.com;
server server2.example.com;
}
...
server {
...
location / {
...
proxy_pass http://my_upstream;
}
}
}
其他特性
Nginx 还有许多其他功能,包括:
静态文件服务
SSL/TLS 加密
Websocket 支持
日志记录和监控
模块化扩展
更多资源
[Nginx 官方文档](http://nginx.org/en/docs/)
[Nginx 教程](http://www.nginx.com/resources/wiki/)
[Nginx 社区论坛](http://forum.nginx.org/)