整活 / 速查 · 25 10 月, 2024 0

Nginx常用反向代理转发配置(WebSocket,WordPress等)

废话不多说,直接上干货。请根据实际需要修改配置。

反向代理WebSocket

location /websocket
{
  proxy_pass http://127.0.0.1:8000;
  proxy_read_timeout 30s;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header Host $host;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection "upgrade";
}

反向代理WordPress

location /
{
  proxy_pass http://127.0.0.1:8000;
  add_header X-Frame-Options SAMEORIGIN;
  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;
  proxy_hide_header X-Frame-Options;
  rewrite /wp-admin$ $scheme://$host$uri/ permanent;
}

反向代理ownCloud等私有网盘

# 设置最大上传大小,防止上传文件超过限制出现413错误
client_max_body_size 10240M;
location / {
  proxy_pass http://127.0.0.1:8000;
  # 省略10000字
}

允许跨域访问

解决“No ‘Access-Control-Allow-Origin’ header”错误。

location / {
  add_header 'Access-Control-Allow-Origin' $http_origin;
  add_header 'Access-Control-Allow-Credentials' 'true';
  add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
  add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
  add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
  if ($request_method = 'OPTIONS') {
      add_header 'Access-Control-Max-Age' 1728000;
      add_header 'Content-Type' 'text/plain; charset=utf-8';
      add_header 'Content-Length' 0;
      return 204;
  }
  # 其他内容
}