I configured a nginx as reverse proxy. I wanna access to a site by two below addresses:
- stats.test.com
- test.com/stats
test.com and stats.test.com located on 2 diffrent servers. my problem is that when client access the site by stats.test.com, every thing is OK and nginx shows client ip. but when client access site by test.com/stats nginx shows the Nginx reverse proxy server IP. frontend configuration for stats.test.com:
upstream stats.test.com{
server 192.168.0.130;
}
server {
include /etc/nginx/default_server_settings;
server_name stats.test.com;
location / {
include /etc/nginx/default_location_settings;
proxy_pass http://stats.test.com;
}
}
frontend configuration for test.com/stats:
upstream test.com{
server 192.168.0.11;
}
upstream stats{
server 192.168.0.130;
}
server {
listen 80 default;
include /etc/nginx/default_server_settings;
server_name test.com;
location / {
include /etc/nginx/default_location_settings;
proxy_pass http://test.com;
}
location /stats/ {
proxy_pass http://stats/;
}
}
backend configuration for stats :
server {
listen 80 default;
access_log /var/log/nginx/stats_access.log;
error_log /var/log/nginx/stats_error.log;
# Disable all methods besides HEAD, GET and POST.
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 444;
}
root /var/www/stats/public_html;
index index.php index.html index.htm;
server_name stats stats.test.com;
location / {
try_files $uri $uri/ /index.html;
}
location /doc/ {
alias /usr/share/doc;
autoindex on;
allow 127.0.0.1;
deny all;
}
location ~* \.(js)$ {
expires 14d;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
location ~\.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
# Return a 404 for all text files.
location ~* ^/(?:README|LICENSE[^.]*|LEGALNOTICE)(?:\.txt)*$ {
return 404;
}
}
I set this in nginx.conf:
set_real_ip_from 192.168.0.2;
real_ip_header X-Forwarded-For
192.168.0.2
is nginx reverse proxy server ip.
In php, you can use instead of $_SERVER["REMOTE_ADDR"] the $_SERVER['HTTP_X_FORWARDED_FOR'] and if you use nginx will appear the ip of the client, not reverse proxy.
I may be wrong but your stats.exemple.com site include the following:
your URI based server is not, I bet that the include default_location_settings file include such proxy_header and proxy settings that do the trick like real_ip_header X-Forwarded-For