我正在使用 nginx 服务器将请求转发到 路由服务,该服务根据 IP 过滤请求。此路由服务返回 403,因为请求中缺少
X-Forwarded-For
标头。这是预期的行为。我正在尝试明确设置此标头,以避免此错误。我在 this repo 的 entrypoint.sh 文件中有以下内容:
#!/bin/bash
set -euo pipefail
# Validate environment variables
#: "${PUBLIC_HOST:?Set PUBLIC_HOST using --env}"
#: "${SERVER:?Set SERVER using --env}"
#: "${SECRET_TOKEN:?Set SECRET_TOKEN using --env}"
: "${SERVER:?Set SERVER using --env}"
echo ">> generating self signed cert"
openssl req -x509 -newkey rsa:4086 \
-subj "/C=XX/ST=XXXX/L=XXXX/O=XXXX/CN=localhost" \
-keyout "/key.pem" \
-out "/cert.pem" \
-days 3650 -nodes -sha256
cat <<EOF >/etc/nginx/nginx.conf
user nginx;
worker_processes 2;
events {
worker_connections 1024;
}
http {
upstream upstream_server{
server ${SERVER};
}
log_format main '\$http_x_forwarded_for - \$remote_user [\$time_local] '
'"\$request" \$status \$body_bytes_sent "\$http_referer" '
'"\$http_user_agent"' ;
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log;
server_tokens off;
server {
listen 443 ssl;
server_name localhost;
ssl_certificate /cert.pem;
ssl_certificate_key /key.pem;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
include /etc/nginx/mime.types;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
set_real_ip_from 172.16.0.0/20;
set_real_ip_from 10.0.0.0/8;
set_real_ip_from 192.168.0.0/16;
client_max_body_size 600M;
location / {
proxy_set_header Host \$host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://upstream_server;
}
}
}
EOF
echo "Running nginx..."
# Launch nginx in the foreground
/usr/sbin/nginx -V -g "daemon off;"
当服务器启动时,它出错,抱怨 proxy_add_x_forwarded_for 是一个unbound variable。我已经尝试根据
this answer将此行更改为
proxy_set_header X-Forwarded-For "$http_x_forwarded_for, $realip_remote_addr";
,但是realip_remote_addr给了我相同的未绑定变量错误。我已经检查过,可以看到 ngx_http_proxy_module 和 realip 模块都在运行,所以我不明白为什么没有获取这些变量。我对 nginx(或 shell 脚本 tbh)的工作不多。我在这里遗漏了一些明显的东西吗?