Nginx转发请求到URL

我试图转发一个http请求到服务器在请求的url中指定,但我总是得到一个404结果。 这是我的configuration:

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 /。

这不是真的如何使用proxy_pass 反向代理 ,但我们假设

 location /proxy { rewrite ^\/proxy\/(.*) $1 break; resolver 8.8.8.8; proxy_pass http://$1/index.html; proxy_redirect off; 

正在工作,请求被代理到$1即服务器在www.google.com ,请求/index.html 。 但是,因为你有

 proxy_set_header Host $host; 

原始Host: localhostwww.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; 

不过,我目前无法testing这个整体configuration。 我只注意到这个单一的错误。

您的代理位置的更好方法将如下所示:

 location ~ /proxy/(.+)$ { proxy_pass http://$1/index.html; } 

但是,这种方法只会为您在URL中指定的任何网站获取/index.html

用这种方法你不需要rewrite语句。