我有一个域,叫它example.com,与path/ test1和/ test2。
http example.com/test1的请求被送到test1.example.com/test1。
http example.com/test2的请求被送到test2.example.com/test2。
这个nginxconfiguration对我的要求工作得很好。
server { listen 80 default_server; root /usr/share/nginx/html; server_name localhost; index index.html; autoindex on; location /test1 { resolver ns1.example.com; resolver_timeout 5s; proxy_pass http://test1.example.com/test1; proxy_redirect default; } location /test2 { resolver ns1.example.com; resolver_timeout 5s; proxy_pass http://test2.example.com/test2; proxy_redirect default; } }
我现在需要改变configuration,如果可能的话,请求将其设置到适当的后端,而不是单独添加到nginxconfiguration。
使用子域而不是path是一个长期的select,但由于其他约束在这个时候不可行。
我宁愿将解决scheme包含在nginxconfiguration中,而不是依靠维护当前example.com主机名的数据库(如果可能的话)。
uripath中的第一个斜杠之后和第二个之前(如果存在)的数据是我需要键入的。
例如:example.com/debug/index.html。 debugging将被parsing出来。 在example.com域中debugging可能是也可能不是有效的主机名。 如果它是无效的(404,500,或502错误..也许其他),然后下降到一个全面的页面。 如果有效,请将请求指向debug.example.com/debug/index.html。
这是我第一次尝试,但不起作用(太多的redirect错误和图像/包括寻找本地文件系统,而不是远程虽然基本的index.html被发现/加载)。
有谁知道我可能会错过什么或知道替代品,这将帮助我达到我的目标?
server { listen 80 default_server; root /usr/share/nginx/html; server_name localhost; index index.html; autoindex on; set $frontend_fqdn "nil"; set $namespace "nil"; if ($request_uri ~ "^/([A-Za-z0-9-_]+).*$") { set $namespace "$1"; set $frontend_fqdn "$namespace.example.com"; } location / { resolver ns1.example.com; resolver_timeout 5s; error_page 404 500 502 = @fallback; if ($frontend_fqdn !~ "nil") { proxy_pass http://$frontend_fqdn$request_uri; } try_files $uri $uri/ =404; } location @fallback { rewrite ^(.*)$ $scheme://$host permanent; } }
预先感谢您的任何帮助。
像这样的东西应该工作:
server { listen 80 default_server; root /usr/share/nginx/html; server_name localhost; index index.html; autoindex on; location ~ ^/([^/]+) { try_files $uri $uri/ @proxy; } location @proxy { resolver ns1.example.com; resolver_timeout 5s; error_page 404 500 502 = @fallback; proxy_pass $scheme://$1.$host; } location @fallback { return 301 $scheme://$host; } }
第一个位置块将匹配所有URI并将path的第一个段保存到$ 1。 然后,它会尝试提供匹配的本地文件/文件夹(如果存在),否则,会尝试通过将path段注入为子域来提示代理服务器。 如果失败,则redirect到预定位置。