[英]Complex nginx rewrite rules for subdomains
I currently have the following (hacky) re-write rule in my nginx.conf to allow dynamic sub-domains to be re-directed to one Django instance. 我目前在我的nginx.conf中有以下(hacky)重写规则,允许动态子域重定向到一个Django实例。
set $subdomain "";
set $subdomain_root "";
set $doit "";
if ($host ~* "^(.+)\.domain\.com$") {
set $subdomain $1;
set $subdomain_root "/profile/$subdomain";
set $doit TR;
}
if (!-f $request_filename) {
set $doit "${doit}UE";
}
if ($doit = TRUE) {
rewrite ^(.*)$ $subdomain_root$1;
break;
}
I'm sure there is a more efficient way to do this but I need to change this rule so that any requests to *.domain.com/media/*
or *.domain.com/downloads/*
go to domain.com/media/*
and domain.com/downloads/*
. 我确信有一种更有效的方法可以做到这一点,但我需要更改此规则,以便任何对
*.domain.com/media/*
或*.domain.com/downloads/*
请求转到domain.com/media/*
和domain.com/downloads/*
。
You can use regular expression server names (see http://nginx.org/en/docs/http/server_names.html#regex_names ) and assign a matching group to a variable $subdomain directly: 您可以使用正则表达式服务器名称(请参阅http://nginx.org/en/docs/http/server_names.html#regex_names )并将匹配的组直接分配给变量$ subdomain:
server {
listen 80;
listen 443;
server_name ~^(?<subdomain>.+)\.domain\.com$
location / {
rewrite ^ /profile/$subdomain$request_uri;
}
}
Actually I think it is much easier to change the nginx re-write rules than to write middleware for django to do this. 实际上我认为更改nginx重写规则比为django编写中间件要容易得多。 After reading up on how nginx processes it's location matching (most exact -> least exact) I created locations for /media and /download as well as a catch all location for / I then moved the rewrite rule to under the / location and simplified it - as I'm no longer worried about checking for files because this entire location is passed to django - the rule becomes :
在了解了nginx如何处理它的位置匹配(最精确 - >最不精确)后,我为/ media和/ download创建了位置以及为/ I捕获所有位置然后将重写规则移到/位置下并简化了它 - 因为我不再担心检查文件,因为整个位置传递给django - 规则变为:
set $subdomain "";
set $subdomain_root "";
if ($host ~* "^(.+)\.domain\.com$") {
set $subdomain $1;
set $subdomain_root "/profile/$subdomain";
rewrite ^(.*)$ $subdomain_root$1;
break;
}
and would probably be even simpler if my nginx\\regex scripting was better :) 如果我的nginx \\ regex脚本更好:)可能会更简单:)
Perhaps a better idea would be to configure django to handle subdomains instead of adding a rewrite in your webserver. 也许更好的想法是配置django来处理子域而不是在你的web服务器中添加重写。 Here's how I did it: http://sharjeel.2scomplement.com/2008/07/24/django-subdomains/
我是这样做的: http : //sharjeel.2scomplement.com/2008/07/24/django-subdomains/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.