Nginx 反向代理配置

Nginx 反向代理配置

反向代理是 Nginx 最常用的功能之一,配置很简单。

1. 什么是反向代理

反向代理就是:用户访问 Nginx,Nginx 把请求转发给后端服务器,再把结果返回给用户。

作用:

  • 隐藏后端服务器
  • 负载均衡
  • 统一入口
  • 缓存静态内容

2. 基本配置

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://127.0.0.1:8080;
        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_pass:后端地址
  • proxy_set_header:传递请求头

3. 常用请求头

location / {
    proxy_pass http://127.0.0.1:8080;

    # 传递域名
    proxy_set_header Host $host;

    # 传递真实IP
    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;
}

4. 超时配置

location / {
    proxy_pass http://127.0.0.1:8080;

    # 连接超时
    proxy_connect_timeout 60s;

    # 发送超时
    proxy_send_timeout 60s;

    # 读取超时
    proxy_read_timeout 60s;
}

5. WebSocket 代理

location /ws {
    proxy_pass http://127.0.0.1:8080;
    proxy_http_version 1.1;

    # WebSocket 升级
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

6. 负载均衡

# 定义后端服务器组
upstream backend {
    server 127.0.0.1:8080 weight=1;
    server 127.0.0.1:8081 weight=2;
    server 127.0.0.1:8082 max_fails=3 fail_timeout=30s;
}

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://backend;
        proxy_set_header Host $host;
    }
}

7. 静态文件直接返回

server {
    listen 80;
    server_name example.com;

    # 静态文件直接处理
    location ~* \.(js|css|png|jpg|gif)$ {
        root /var/www/static;
        expires 30d;
    }

    # 其他请求转发后端
    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
    }
}

8. 配置生效

# 检查配置
nginx -t

# 重载配置
nginx -s reload

9. 常见问题

1)502 Bad Gateway

  • 后端服务没启动
  • 后端端口不对
  • 后端超时

2)504 Gateway Timeout

  • 后端处理太慢
  • 调整超时时间

3)获取不到真实IP

  • 没配置 X-Real-IP
  • 后端没读取请求头

4)WebSocket 连不上

  • 没配置 Upgrade 和 Connection 头

10. 生产建议

1)一定要传请求头

  • Host
  • X-Real-IP
  • X-Forwarded-For

2)合理设置超时

  • 根据业务调整
  • 不要太长也不要太短

3)静态文件 Nginx 直接处理

  • 减轻后端压力
  • 提高性能

4)开启 gzip 压缩

gzip on;
gzip_types text/css application/javascript;

总结

Nginx 反向代理配置要点:

  • proxy_pass 指定后端地址
  • 一定要传请求头
  • 常用超时配置
  • WebSocket 要升级头
  • upstream 做负载均衡
  • 静态文件直接返回
  • 配置完 nginx -t 检查
  • 502 检查后端是否启动
  • 生产环境传全请求头

反向代理是 Nginx 基本功,一定要熟练掌握。


emer 发布于  2026-10-9 07:30 

PHP session不生效,cookie配置检查

前言

PHP用session存用户登录状态,结果刷新页面就掉了?session不生效太常见了,一般就是cookie配置不对、路径不对、或者目录没权限。本文讲怎么排查和解决。

一、session工作原理

简单说:

  1. 浏览器访问网站
  2. PHP创建session,生成session_id
  3. session_id通过cookie发给浏览器
  4. 浏览器每次请求带上这个cookie
  5. PHP根据cookie里的session_id找到对应数据

核心: session靠cookie传session_id,cookie不行session就没了。

二、常见原因

原因1:cookie没设置对

session.cookie_path、session.cookie_domain配置不对。

原因2:session保存目录没权限

session文件存不进去。

原因3:session.auto_start没开

或者开了但和代码冲突。

原因4:跨域问题

主域和子域之间cookie不共享。

原因5:HTTPS下cookie的secure问题

cookie设了secure,但用http访问。

三、排查步骤

第一步:检查session有没有启动

<?php
session_start();

// 存个值
$_SESSION['test'] = 'hello';

// 看有没有
echo '<pre>';
print_r($_SESSION);
echo '</pre>';

刷新页面,看test还在不在。

第二步:看cookie里有没有PHPSESSID

按F12打开浏览器开发者工具 → Application → Cookies。

看有没有 PHPSESSID 这个cookie。

没有的话: 就是cookie没设对。

有的话: 那就是session保存目录的问题。

四、php.ini配置检查

找到php.ini位置

php --ini

关键配置

;session保存目录
session.save_path = "/var/lib/php/session"

;是否自动启动
session.auto_start = 0

;cookie路径
session.cookie_path = /

;cookie域名
session.cookie_domain =

;cookie有效期(秒)
session.cookie_lifetime = 0

;是否仅https
session.cookie_secure = 0

;是否仅http(防XSS)
session.cookie_httponly = 1

五、常见坑和解决

坑1:session目录没权限

session文件写不进去。

检查:

ls -ld /var/lib/php/session

解决:

chmod 777 /var/lib/php/session
chown apache:apache /var/lib/php/session

或者看php-fpm用的哪个用户。

坑2:cookie_path不对

比如网站装在子目录,但cookie_path设成了别的。

解决:

ini_set('session.cookie_path', '/');
session_start();

坑3:cookie_domain不对

多域名访问时,cookie只在一个域名下有效。

解决:

ini_set('session.cookie_domain', '.example.com');

注意前面有个点,表示所有子域名都生效。

坑4:HTTPS下设了secure

cookie_secure=1表示只在https下传cookie,用http访问就没了。

解决:

session.cookie_secure = 0

或者全站用https。

坑5:session.auto_start冲突

代码里已经session_start()了,但php.ini里也开了auto_start,冲突。

解决:

session.auto_start = 0

六、代码里动态设置

不想改php.ini,可以在代码里设:

<?php
// 必须在session_start()之前

ini_set('session.cookie_path', '/');
ini_set('session.cookie_domain', '.example.com');
ini_set('session.cookie_lifetime', 0);

session_start();

$_SESSION['user_id'] = 1;

七、检查session是否生效

写个测试页:

<?php
session_start();

// 第一次访问,设置
if (!isset($_SESSION['count'])) {
    $_SESSION['count'] = 1;
} else {
    $_SESSION['count']++;
}

echo "访问次数: " . $_SESSION['count'];
echo "<br>";
echo "Session ID: " . session_id();
echo "<br>";
echo "Session 文件: " . session_save_path() . "/sess_" . session_id();

刷新页面,数字应该一直涨。

如果不涨: 就是session没存住。

八、常见场景

场景1:登录后刷新就掉

原因: cookie_path或domain不对。

解决: 检查cookie配置。

场景2:换了个子域名就掉

比如 www.example.com 登录了,跳到 bbs.example.com 就没登录。

原因: cookie_domain没设成 .example.com。

解决:

ini_set('session.cookie_domain', '.example.com');

场景3:从http跳到https就掉

原因: cookie_secure=1,但http不带cookie。

解决: 全站用https,或者关掉secure。

场景4:session目录满了

原因: session文件太多。

解决: 清理旧session,或者设gc_maxlifetime。

session.gc_maxlifetime = 1440

九、快速排查清单

  1. F12看cookie里有没有PHPSESSID
  2. 没有 → 查cookie_path、cookie_domain、cookie_secure
  3. 有 → 查session目录权限
  4. 都没问题 → 看session.auto_start有没有冲突
  5. 跨域问题 → cookie_domain设成 .主域名

总结

记住:

  1. session靠cookie传session_id
  2. 先看cookie里有没有PHPSESSID
  3. 没有就查cookie配置
  4. 有就查session目录权限
  5. 跨域名记得设cookie_domain=.主域名

最常用:

ini_set('session.cookie_path', '/');
session_start();

遇到问题加QQ23979811 协助处理


emer 发布于  2026-10-9 07:27 

Nginx 访问日志配置

Nginx 访问日志配置

访问日志是排查问题和分析流量的重要依据,配置好很有必要。

1. 默认日志位置

# 访问日志
/var/log/nginx/access.log

# 错误日志
/var/log/nginx/error.log

2. 日志格式

Nginx 默认有两种日志格式:

combined(默认)

log_format combined '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent"';

common

log_format common '$remote_addr [$time_local] "$request" $status $body_bytes_sent';

3. 自定义日志格式

在 nginx.conf 的 http 块添加:

http {
    log_format main '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent" '
                    '$request_time $upstream_response_time';

    access_log /var/log/nginx/access.log main;
}

4. 常用日志变量

  • $remote_addr: 客户端IP
  • $time_local: 本地时间
  • $request: 请求行
  • $status: 状态码
  • $body_bytes_sent: 发送字节数
  • $http_referer: 来源页面
  • $http_user_agent: 浏览器信息
  • $request_time: 请求总耗时
  • $upstream_response_time: 后端响应时间

5. 按站点分开日志

不同站点用不同日志文件:

server {
    listen 80;
    server_name a.com;
    access_log /var/log/nginx/a.access.log;
}

server {
    listen 80;
    server_name b.com;
    access_log /var/log/nginx/b.access.log;
}

6. 关闭日志

静态资源不记日志:

location ~* \.(jpg|jpeg|png|gif|css|js)$ {
    access_log off;
}

7. 日志切割

Nginx 自带日志切割:

http {
    # 每天切割,保留30天
    access_log /var/log/nginx/access.log main;
    log_not_found off;
}

也可以用 logrotate:

# 配置文件
/etc/logrotate.d/nginx

8. 分析日志

统计访问量

# 统计总请求数
wc -l /var/log/nginx/access.log

# 统计独立IP
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn

统计状态码

awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c

统计访问最多的URL

awk '{print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -10

总结

Nginx 访问日志配置要点:

  • 默认日志在 /var/log/nginx/
  • combined 是默认格式
  • 自定义格式添加 $request_time 等变量
  • 不同站点分开日志文件
  • 静态资源可以关闭日志
  • 日志要定期切割
  • 用 awk 分析日志很方便

做好日志配置,排查问题和分析流量都有用。


emer 发布于  2026-10-9 07:24 

Nginx 反向代理原理

Nginx 反向代理原理

反向代理是 Nginx 最常用的功能,搞懂原理很有必要。

1. 什么是反向代理

正向代理:代理客户端,比如翻墙工具。
反向代理:代理服务器,客户端不知道真实服务器。

用户请求 Nginx,Nginx 再转发给后端服务器,用户以为自己直接访问的就是 Nginx。

2. 为什么用反向代理

1)隐藏真实服务器

  • 后端服务器 IP 不暴露
  • 更安全

2)负载均衡

  • 多个后端服务器分摊请求
  • 提高并发能力

3)统一入口

  • 多个服务用一个域名
  • 不同路径转发到不同服务

4)SSL 卸载

  • HTTPS 证书在 Nginx 配置
  • 后端用 HTTP 就行

5)缓存静态内容

  • Nginx 直接返回静态资源
  • 减轻后端压力

3. 基本配置

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

4. 常用代理头

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;

后端通过这些头获取真实客户端信息。

5. 路径转发示例

# 根路径转发到PHP服务
location / {
    proxy_pass http://127.0.0.1:8080;
}

# /api 转发到后端接口
location /api/ {
    proxy_pass http://127.0.0.1:3000/;
}

# /static 直接读本地文件
location /static/ {
    root /var/www;
}

6. 超时设置

# 连接超时
proxy_connect_timeout 60s;

# 读取超时
proxy_read_timeout 60s;

# 发送超时
proxy_send_timeout 60s;

7. 常见问题

1)后端获取不到真实IP

  • 检查 X-Real-IP 头是否设置
  • 后端代码是否读取这个头

2)WebSocket 连接失败

  • 需要添加 Upgrade 头
  • 配置 HTTP/1.1
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_http_version 1.1;

3)大文件上传失败

  • 修改 client_max_body_size
  • 增加 proxy_read_timeout

总结

Nginx 反向代理要点:

  • 代理服务器,隐藏真实后端
  • 实现负载均衡、统一入口
  • 配置 proxy_pass 转发
  • 记得设置常用代理头
  • 后端通过请求头获取真实客户端信息
  • 注意超时和上传大小限制
  • WebSocket 需要特殊配置

做 Web 开发,反向代理是必备技能。


emer 发布于  2026-10-9 07:12 

Nginx 反向代理配置

Nginx 反向代理配置

反向代理是 Nginx 最常用的功能,前端请求 Nginx,Nginx 再转发给后端服务。

1. 什么是反向代理

  • 正向代理: 代理客户端,比如翻墙
  • 反向代理: 代理服务器,客户端不知道真正的后端

2. 基础配置

server {
    listen 80;
    server_name www.example.com;

    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

意思是:访问 80 端口的请求,转发到 8080 端口的服务。

3. 常用配置说明

location / {
    # 转发地址
    proxy_pass http://127.0.0.1:8080;

    # 传递真实IP
    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_connect_timeout 5s;
    proxy_read_timeout 60s;
    proxy_send_timeout 60s;
}

4. 按路径转发不同服务

# 访问 /api/ 转发到后端API服务
location /api/ {
    proxy_pass http://127.0.0.1:8080;
}

# 访问 /admin/ 转发到后台管理服务
location /admin/ {
    proxy_pass http://127.0.0.1:8081;
}

# 其他访问静态文件
location / {
    root /www/wwwroot/html;
}

5. 常见应用场景

1)前后端分离:

  • 前端静态文件 Nginx 直接处理
  • API 请求转发到后端服务

2)Node.js/Python 后端:

  • Nginx 处理 80/443 端口
  • 转发到 Node.js 的 3000 端口

3)负载均衡:

  • 配合 upstream 转发到多台服务器

6. 常见问题

1)后端获取不到真实 IP:

  • 要配置 X-Real-IP 和 X-Forwarded-For
  • 后端从请求头里取

2)WebSocket 不支持:

  • 需要加特殊头
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";

3)上传文件大小限制:

client_max_body_size 100m;

总结

Nginx 反向代理核心:

  • proxy_pass 转发地址
  • proxy_set_header 传递真实信息
  • 按 location 转发不同服务
  • 注意超时和文件大小限制

做 Web 开发,Nginx 反向代理一定要会配置。


emer 发布于  2026-10-8 07:10 

Nginx设置默认首页,index.html配置

前言

访问网站根目录,Nginx 不知道默认打开哪个文件,就返回 403 或者 404。这是因为没配置默认首页。本文讲一下 Nginx 怎么设置默认首页。

什么是默认首页

用户访问 www.example.com/,Nginx 自动找目录下的 index.html 打开,不用手动输入文件名。

配置方法

用 index 指令设置:

server {
    listen       80;
    server_name  www.example.com;

    root  /var/www/html;
    index index.html;
}

多个默认首页

Nginx 会按顺序找,找到第一个存在的就用:

index index.html index.htm index.php;

意思是:先找 index.html,没有就找 index.htm,再没有就找 index.php。

完整站点配置

server {
    listen       80;
    server_name  www.example.com;

    root  /var/www/html;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        fastcgi_pass   unix:/run/php-fpm/www.sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}

自定义默认首页

不想用 index.html,想用别的文件名?

index default.html;

这样访问根目录就打开 default.html。

常见坑

坑1:访问根目录 403 Forbidden

配置了 root,也放了 index.html,但访问还是 403。

原因1: 文件名写错了,比如是 Index.html(大写 I)。

解决: Linux 区分大小写,文件名必须和 index 配置一致。

原因2: 文件权限不对。

解决: 确保文件权限是 644,目录是 755。

坑2:默认首页不生效

改了 index 配置,但还是打开旧的首页。

原因: 没重载 Nginx。

解决:

nginx -s reload

坑3:PHP 首页不解析

默认首页设成 index.php,但访问直接下载 PHP 文件。

原因: PHP 解析配置没写对。

解决: 确保有 PHP 的 location 配置:

location ~ \.php$ {
    fastcgi_pass   unix:/run/php-fpm/www.sock;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include        fastcgi_params;
}

坑4:静态首页和 PHP 首页顺序

index 里先写 index.html 还是 index.php?

建议: 把常用的放前面。如果主要是 PHP 程序,就把 index.php 放前面。

总结

一行配置搞定:

index index.php index.html index.htm;

记住: index 后面跟多个文件名,Nginx 按顺序找,找到第一个存在的就用。

遇到问题加QQ23979811 协助处理


emer 发布于  2026-10-7 07:38 

Nginx 配置 HTTPS 详解

Nginx 配置 HTTPS 详解

现在网站都要求上 HTTPS,Nginx 配置 HTTPS 是运维必备技能。

1. 申请 SSL 证书

免费证书推荐:

  • Let's Encrypt(免费 90 天)
  • 阿里云/腾讯云免费 DV 证书

用 acme.sh 申请 Let's Encrypt:

# 安装 acme.sh
curl https://get.acme.sh | sh

# 申请证书
~/.acme.sh/acme.sh --issue -d www.example.com --webroot /www/wwwroot/example.com/

# 安装证书
~/.acme.sh/acme.sh --install-cert -d www.example.com \
  --key-file /www/server/ssl/private.key \
  --fullchain-file /www/server/ssl/cert.crt

2. Nginx 基础 HTTPS 配置

server {
    listen 443 ssl;
    server_name www.example.com;

    # 证书文件
    ssl_certificate     /www/server/ssl/cert.crt;
    ssl_certificate_key /www/server/ssl/private.key;

    # SSL 优化
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    root /www/wwwroot/example.com;
    index index.html index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

3. HTTP 自动跳转 HTTPS

server {
    listen 80;
    server_name www.example.com;
    return 301 https://$server_name$request_uri;
}

4. 优化 HTTPS 性能

开启 HTTP/2:

listen 443 ssl http2;

HSTS 强制 HTTPS:

add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

开启 OCSP Stapling:

ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 114.114.114.114 valid=300s;

5. 常见问题

1)证书不生效:

  • 检查证书路径对不对
  • 证书文件格式是否正确
  • Nginx 配置重载了吗

2)混合内容问题:

  • 页面里有 http:// 的资源,浏览器会拦截
  • 全部改成 https:// 或 // 协议相对路径

3)证书过期:

  • 免费证书 90 天过期
  • 用 acme.sh 自动续期
# acme.sh 自动安装了定时任务
crontab -l | grep acme

6. 检查配置

# 检查 Nginx 配置
nginx -t

# 重载配置
nginx -s reload

# 测试证书
curl -I https://www.example.com

总结

Nginx 配置 HTTPS 要点:

  • 申请 SSL 证书
  • 配置 443 端口和证书路径
  • HTTP 跳转 HTTPS
  • 开启 HTTP/2 和 SSL 优化
  • 设置自动续期

现在没有 HTTPS 的网站浏览器都标"不安全",赶紧给网站配上。


emer 发布于  2026-10-7 07:10 
'); })();