安装
安装完后,配置文件默认在
# debian
apt-get install nginx
# centos
yum install epel-release -y # 默认仓库中没有,需要启动epel (extra packages for enterprize linux)
yum install nginx -y
配置
主配置文件位于/etc/nginx/nginx.conf
,虚拟主机的配置在/etc/nginx/conf.d/
下。
Nginx 配置文件由多个区块(blocks)组成,主要包括以下几部分:
-
全局上下文(Global Context)
这个部分用于配置一些全局的设置,如日志路径、工作进程数等。 -
HTTP上下文(HTTP Context)
HTTP 上下文包含 Web 服务器的全局 HTTP 配置,可以包含各种指令,如代理设置、虚拟主机配置、缓存设置等。 -
Server上下文(Server Context)
Server 块用于定义虚拟主机的配置,可以包含针对特定域名或 IP 地址的设置。 -
Location上下文(Location Context)
Location 块用于定义 URL 路径的具体处理方式。通常它们嵌套在 Server 块内部,用于匹配请求的 URI 并决定如何处理。
文档地址:https://nginx.org/en/docs/
# 全局上下文
user nginx; # 指定工作进程的用户
worker_processes auto; # 自动设置工作进程数
error_log /var/log/nginx/error.log warn; # 错误日志
pid /var/run/nginx.pid; # 存储 Nginx 进程 ID 的文件
# 工作模式及事件模块配置
events {
worker_connections 1024; # 每个 worker 进程的最大连接数
}
# HTTP 模块配置
http {
include /etc/nginx/mime.types; # 设置 MIME 类型
default_type application/octet-stream; # 默认 MIME 类型
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"'; # 日志格式
access_log /var/log/nginx/access.log main; # 访问日志
sendfile on; # 启用 sendfile 加速文件传输
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# 压缩设置
gzip on;
gzip_disable "msie6"; # 禁用 IE6 的 gzip 压缩
include /etc/nginx/conf.d/*.conf; # 加载 conf.d 目录下的所有配置文件
# 服务器配置
server {
listen 80; # 监听 80 端口
server_name example.com; # 服务器域名
# 网站根目录
root /usr/share/nginx/html;
index index.html index.htm;
# 错误页面
error_page 404 /404.html;
location = /404.html {
root /usr/share/nginx/html;
}
# 正常请求的处理
location / {
try_files $uri $uri/ =404;
}
# 反向代理配置示例
location /api/ {
proxy_pass http://localhost:5000; # 反向代理到本地的 5000 端口
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}
location优先级
# 1. 精确匹配 ( = )
location = /foo {
# 只有请求 "/foo" 时才会匹配
}
# 2. 前缀匹配 ( ^~ )
location ^~ /images/ {
# 请求的 URI 以 "/images/" 开头时匹配
}
# 3. 正则匹配 ( ~ 和 ~* )
location ~ /foo\d+ {
# 请求的 URI 匹配正则表达式 "/foo" 后跟一个或多个数字
}
location ~* /bar {
# 请求的 URI 匹配正则表达式 "/bar",不区分大小写
}
# 4. 普通匹配
location /foo/ {
# 匹配路径汇总含有 /foo/ 的URI
}
常用配置
反向代理配置
location /api/ {
proxy_pass http://localhost:5000;
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-Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
# 对于流式接口,需要禁用缓冲
proxy_buffering off;
proxy_redirect off;
}
转发tcp
/etc/nginx/nginx.conf
worker_processes 1;
events {
worker_connections 10000;
}
stream {
log_format proxy_logs '$remote_addr [$time_local] '
'$protocol $status $bytes_sent $bytes_received '
'$session_time';
access_log /var/log/nginx/stream_access.log proxy_logs;
error_log /var/log/nginx/stream_error.log info;
upstream mysql_upstream {
server 10.181.15.158:3306;
}
server {
listen 80;
proxy_pass mysql_upstream;
}
}
子路径
使用alias不会拼接location部分的路径,路径需要以/
结尾。index可以直接写相对路径 index.html 或者绝对路径 /h5/index.html,如果你写/index.html,则会被location /规则拦截。
location = /h5 {
return 301 /h5/;
}
location ^~ /h5/ {
alias /data/repo/voice-h5/; # 网站根目录
index index.html;
}
如果你用root,则需要添加一条rewrite规则
location ^~ /h5/ {
rewrite ^/h5/(.*)$ /$1 break;
root /data/repo/voice-h5/;
index /h5/index.html;
}
负载均衡
通过 upstream 块定义后端服务器池,常见负载均衡方式包括轮询、加权、IP 哈希等。
详细配置参见:https://nginx.org/en/docs/http/ngx_http_upstream_module.html
upstream backend {
ip_hash; # 启用 IP 哈希
server backend1.example.com;
server backend2.example.com;
}
server {
location / {
proxy_pass http://backend;
}
}
配置HTTPS
server {
listen 443 ssl;
server_name demo.com;
ssl_certificate /etc/nginx/ssl/demo.com.crt;
ssl_certificate_key /etc/nginx/ssl/demo.com.key;
# 其他配置...
}
其它
动态配置
#! /bin/sh
# apt-get install gettext
defined_envs=$(printf '${%s} ' $(env | cut -d= -f1))
envsubst "$defined_envs" < /etc/nginx/conf.d/demo.conf.template > /etc/nginx/conf.d/demo.conf
exec /usr/sbin/nginx -g 'daemon off;'
自签名证书
# 1. 安装 OpenSSL
sudo yum install openssl # CentOS/RHEL
sudo apt-get install openssl # Ubuntu/Debian
# 2. 创建 OpenSSL 配置文件
mkdir demo_cert
cd demo_cert
cat << EOF > openssl.cnf
[ req ]
default_bits = 2048
default_keyfile = privkey.pem
distinguished_name = req_distinguished_name
x509_extensions = v3_ca
[ req_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = CN
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = GuangDong
localityName = Locality Name (eg, city)
localityName_default = ShenZhen
organizationName = Organization Name (eg, company)
organizationName_default = Fake Company Name
commonName = Common Name (e.g. server FQDN or YOUR name)
commonName_default = *.demo.com
commonName_max = 64
[ v3_ca ]
subjectAltName = @alt_names
keyUsage = digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth, clientAuth
[ alt_names ]
DNS.1 = *.demo.com
DNS.2 = demo.com
EOF
# 3. 生成私钥和证书签署请求(CSR)
openssl genpkey -algorithm RSA -out demo.com.key
# openssl genpkey -algorithm RSA -out demo.com.key -aes256 # 这个会要输入密码
openssl req -new -key demo.com.key -out demo.com.csr -config openssl.cnf
# 4. 自签名证书
openssl x509 -req -in demo.com.csr -signkey demo.com.key -out demo.com.crt -days 3650 -extensions v3_ca -extfile openssl.cnf
# 5. 验证 (可选)
openssl x509 -in demo.com.crt -text -noout
# 6. 配置ng (demo.com.crt 和 demo.com.key)
# 将私钥密码解除
openssl rsa -in /path/to/encrypted.key -out /path/to/decrypted.key
代理gradio
如果想代理为某个子路径,可以参考:https://www.gradio.app/guides/running-gradio-on-your-web-server-with-nginx
如果你的网络代理层数较多,中间层可能没有传递 X-Forwarded-Proto,可以在最末层的NG写死 https
server {
listen 80;
server_name example.com www.example.com; # Change this to your domain name
location / { # Change this if you'd like to server your Gradio app on a different path
proxy_pass http://127.0.0.1:7860; # Change this if your Gradio app will be running on a different port
proxy_buffering off;
proxy_redirect off;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
}
}