Nginx – 将任何子域redirect到文件而不重写

最近,我已经从Apache切换到Nginx,以提高运行Ubuntu 11.10的Web服务器的性能。 我一直在试图弄清楚Nginx与Apache相比有些什么问题,但是有一个问题一直困扰着我,我一直没能在网上find答案。 我的问题是,我需要能够redirect(而不是重写)任何子域到一个文件,但该文件需要能够获得的URL的子域的一部分,以便做一个数据库查找那个子域。 到目前为止,我已经能够得到任何子域重写到该文件,但是,然后它丢失我所需要的子域的文本。

所以,例如,我想test.server.comredirect到server.com/resolve.php,但仍然保持为test.server.com。 如果这是不可能的,那么我至less需要的东西就是诸如去test.server.com去server.com/resolve.php?=test的东西。 其中一个选项必须在Nginx中可能。

我的configuration现在看起来像这样:

server { listen 80; ## listen for ipv4; this line is default and implied listen [::]:80 default ipv6only=on; ## listen for ipv6 root /usr/share/nginx/www; index index.php index.html index.htm; # Make site accessible from http://localhost/ server_name www.server.com server.com; location / { # First attempt to serve request as file, then # as directory, then fall back to index.html try_files $uri $uri/ /index.html; } location /doc { root /usr/share; autoindex on; allow 127.0.0.1; } location /images { root /usr/share; autoindex off; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # #error_page 500 502 503 504 /50x.html; #location = /50x.html { # root /usr/share/nginx/www; #} # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # location ~ \.php$ { fastcgi_pass unix:/tmp/php5-fpm.sock; fastcgi_index index.php; include fastcgi_params; } # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { # deny all; #} } server { listen 80 default; server_name *.server.com; rewrite ^ http://www.server.com/resolve.php; } 

正如我之前所说的,我对Nginx来说是非常新的,所以我有一种感觉,答案很简单,但是在线例子似乎没有涉及到redirect,而没有重写或者用子域部分重写。 任何对做什么的帮助将是最受赞赏的,如果任何人有一个更好的主意来完成我所需要的,我也开放的想法。 非常感谢你。

捕获子域并将其作为查询parameter passing相当容易。

test.server.com – > server.com/resolve.php?sub=test

 server { listen 80 default; server_name ~^(?<sub>.+)\.server\.com$; rewrite ^ http://www.server.com/resolve.php?sub=$sub } 

本质上,使用命名正则expression式捕获将子域分配给variables,然后将该variables作为查询parameter passing给您的redirect。

redirect并保持相同的server_name基本上需要覆盖nginx(在你的fastcgi_params中)所做的SERVER_NAME $server_name的默认分配。 困难在于在服务器块之间传递你的子域名。