我正在尝试将 http 请求转发到请求 URL 中指定的服务器,但结果总是 404。这是我的配置:
worker_processes 2;
daemon off;
error_log /var/log/nginx.error_log info;
events {
worker_connections 1000;
# use [ kqueue | epoll | /dev/poll | select | poll ];
use epoll;
}
http {
include mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$gzip_ratio"';
log_format download '$remote_addr - $remote_user [$time_local] '
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$http_range" "$sent_http_content_range"';
client_header_timeout 3m;
client_body_timeout 3m;
send_timeout 3m;
client_header_buffer_size 1k;
large_client_header_buffers 4 4k;
gzip on;
gzip_min_length 1100;
gzip_buffers 4 8k;
gzip_types text/plain;
output_buffers 1 32k;
postpone_output 1460;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
send_lowat 12000;
keepalive_timeout 75 20;
#lingering_time 30;
#lingering_timeout 10;
#reset_timedout_connection on;
server {
listen 80;
#server_name one.example.com www.one.example.com;
access_log /var/log/nginx.access_log main;
location /proxy {
rewrite ^\/proxy\/(.*) $1 break;
resolver 8.8.8.8;
proxy_pass http://$1/index.html;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
#proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 10m;
client_body_buffer_size 128k;
#client_body_temp_path /var/nginx/client_body_temp;
proxy_connect_timeout 70;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_send_lowat 12000;
#proxy_buffering off;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
#proxy_temp_path /var/nginx/proxy_temp;
charset koi8-r;
}
}
}
例如http://localhost/proxy/www.google.com返回 404,url/未找到。
答案1
这实际上并不是反向代理proxy_pass
应该使用with ,但我们假设
location /proxy {
rewrite ^\/proxy\/(.*) $1 break;
resolver 8.8.8.8;
proxy_pass http://$1/index.html;
proxy_redirect off;
正常运行,请求被代理到$1
ie 服务器www.google.com
,请求/index.html
。但是,由于您有
proxy_set_header Host $host;
原始Host: localhost
请求来自www.google.com
:
GET /index.html HTTP/1.1
Host: localhost
因为你需要请求
GET /index.html HTTP/1.1
Host: www.google.com
相反,你更愿意
proxy_set_header Host $1;
不过,我目前无法测试这个整体配置;我只是注意到了这个错误。
答案2
对于代理位置,更好的方法如下:
location ~ /proxy/(.+)$ {
proxy_pass http://$1/index.html;
}
但是,这种方法只能获取您/index.html
在 URL 中指定的任何网站。
采用这种方法您就不需要声明了rewrite
。