Aaron Lau(韩栖)

Nginx 学习笔记 (2) —— 反向代理基本配置

366 字

1) Nginx 配置文件的路径,可透过 nginx -t 命令找出。nginx.conf 的内容相当庞杂,为日后维护方便,建议拆分出 server block,即在 http block 引用外部配置文件;

http {
    ...
    include server.conf;
    ...
}

2) 以反代 www.example.com 为例。proxy_pass 遇有变量是不会走系统 /etc/hosts 和 /etc/resolv.conf 的,而是走 resolver 指定的 DNS 服务器,好处是可以实现域名的动态解析。

出于防止跨站攻击和反盗链的目的,对方一般会校验 Referer,不是他们的域名统统返回 403,作出修改可绕过此限制。X-Real-IP 用于记录客户端的 IP(但不一定是真实的),X-Forwarded-For 则反映链路信息,两者的伪造相当容易,毕竟作弊在应用层是难免的。借由传递 Set-Cookie,既可反代又不影响注册登录等功能运作。

server {
    listen 80;
    server_name yourdomain.com;

    location / {
        resolver 8.8.8.8;
        set $TARGET 'www.example.com';
        proxy_pass http://$TARGET;

        # proxy_set_header Host $TARGET;
        proxy_set_header Referer http://$TARGET;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_pass_header Set-Cookie;
        # proxy_cookie_domain www.example.com yourdomain.com;
    }
}

3) 先检测配置文件语法,再热加载或重启 Nginx;从外部访问,还需要打开 firewalld 防火墙的相应端口。

nginx -t && (nginx -s reload || service nginx restart)
firewall-cmd --add-service=http --add-service=https --permanent
firewall-cmd --reload

<small>原载 App-scope,有删改。</small>

App-scope · 教程 · Nginx