Nginx正向代理,且apache或nginx提供客户端原始IP

原创
小哥 3年前 (2022-11-02) 阅读数 162 #PHP
文章标签 PHP

Nginx反向代理配置信息

PROXY-START/

location /
{
proxy_pass http://192.168.139.129;
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 REMOTE-HOST $remote_addr;

add_header X-Cache $upstream_cache_status;

Set Nginx Cache

add_header Cache-Control no-cache;
expires 12h;
}

PROXY-END/

apache获取真实IP配置信息

<VirtualHost *:80>
ServerAdmin webmaster@example.com
DocumentRoot "/www/wwwroot/ceshidaili/public"
ServerName 6bcadd09.ceshidaili.local
ServerAlias ceshidaili.local

errorDocument 404 /404.html

ErrorLog "/www/wwwlogs/ceshidaili.local-error_log"
CustomLog "/www/wwwlogs/ceshidaili.local-access_log" combined

DENY FILES

<Files ~ (.user.ini|.htaccess|.git|.svn|.project|LICENSE|README.md)$>
Order allow,deny
Deny from all

PHP

<FilesMatch .php$>
SetHandler "proxy:unix:/tmp/php-cgi-73.sock|fcgi://localhost"

PATH

<Directory "/www/wwwroot/ceshidaili/public">
SetOutputFilter DEFLATE
Options FollowSymLinks
Require all granted
DirectoryIndex index.php index.html index.htm default.php default.html default.htm
AllowOverride all

<IfModule remoteip_module>
RemoteIPHeader X-Forwarded-For
RemoteIPInternalProxy 192.168.139.128/24

Nginx 获取真实IP配置信息

real_ip_header X-Forwarded-For;

set_real_ip_from 192.168.139.128/24;

补充:

一层代理可以用X-Forwarded-For或者X-Real-IP

多次代理建议用X-Real-IP

X-Forwarded-For 是用于记录代理信息的,每经过一级代理(匿名代理除外),代理服务器都会把这次请求的来源IP追加在 X-Forwarded-For

X-Real-IP,一般只记录真实发出请求的客户端IP

请求头信息丢失可能问题:

方法一:NGINX代理时加上请求头信息:

location /
{
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 http://192.168.18.72/mkh5;
}
由于前端代码request的header中包含_,所以这个配置没有生效

方法二:

从根本解除nginx的限制,nginx默认request的header的那么中包含’_’时,会自动忽略掉。

http部分中添加如下配置:underscores_in_headers on; (默认 underscores_in_headers 为off)

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除