Nginx:通配符子网域将URLredirect到带请求的页面

我想转换:

http://test.example.com/file.php

要么

http://www.example.com/file.php?subdomain=test

要么

http://test.example.com/file.php?subdomain=test

取决于哪个更简单或更快

这适用于索引页面,但对于子文件夹和文件,它将在redirect循环中获得。

server { listen 80; # Make site accessible from http://localhost/ server_name ~^[^.]+.example.com$; rewrite ^/(.*)/$ /$1 permanent; if ($host ~* ^([^.]+).example.com$) { set $subdomain $1; } rewrite ^(.*)$ $1?subdomain=$subdomain last; location / { root /var/www/example.com; index index.html index.php; } location ~ \.php$ { try_files $uri =404; root /var/www/example.com; fastcgi_pass unix:/var/run/php-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script include fastcgi_params; } } 

我不太清楚你的目标是什么 – 因为你的例子显示了两种可能性。 下面的configuration(未经testing)应该会导致:

 http://test.example.com/file.php ==> http://www.example.com/file.php?subdomain=test 

它应该匹配任何子域和任何文件名。

 server{ server_name www.example.com; root /var/www/example.com; index index.html index.php; location ~ \.php$ { try_files $uri =404; fastcgi_pass unix:/var/run/php-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script include fastcgi_params; } } server { server_name "~^(?<subdomain>.+)\.example\.com$"; rewrite ^/(.*?)/?$ http://www.example.com/$1?subdomain=$subdomain; } 

简要解释:

  • 静态server_names在regex之前匹配 – 所以,任何对www.example.com的请求都将由第一个服务器块处理
  • 根和索引指令应放置在服务器块(不是位置块)下,如果可能的话
  • 端口80不需要listen指令
  • 第二个服务器块使用命名捕获将子域分配给variables
  • 重写捕获从第一个斜杠到最后的所有内容,不包括两者((。*?)是懒惰的)。

(顺便说一下,我真的不太确定你的configuration应该如何做一个目录或静态文件的情况。目前,下面应该会发生(这似乎不明智):

 http://test.example.com/file.jpg ==> http://www.example.com/file.jpg?subdomain=test http://test.example.com/path/to/subfolder/ ==> http://www.example.com/path/to/subfolder?subdomain=test 

它看起来像你当前的configuration是一样的。 添加几个你想要的例子,我可能能够更新这个configuration更相关)。